diff --git a/crates/forge-core/src/rules.rs b/crates/forge-core/src/rules.rs index b39f275ec..5c4029f7b 100644 --- a/crates/forge-core/src/rules.rs +++ b/crates/forge-core/src/rules.rs @@ -1487,6 +1487,14 @@ mod tests { copies: Vec, } + #[derive(Debug, Deserialize, Serialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct V2PackListInput { + copies: Vec, + #[serde(default)] + as_of: Option, + } + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ApprovalsInput { @@ -1617,6 +1625,11 @@ mod tests { ); } } + "v2_pack_list" => { + let inp: V2PackListInput = input(v); + let got = v2::v2_pack_list(&inp.copies, inp.as_of.as_ref()); + assert_eq!(got, expected::>(v), "vector `{ctx}`"); + } "approvals" => { let inp: ApprovalsInput = input(v); let oracle = v2::RoleOracle::new(inp.memberships); diff --git a/crates/forge-core/src/rules/v2.rs b/crates/forge-core/src/rules/v2.rs index b1a52daff..9962feb2e 100644 --- a/crates/forge-core/src/rules/v2.rs +++ b/crates/forge-core/src/rules/v2.rs @@ -347,6 +347,181 @@ pub fn pack_read_order(copies: &[PackCopy]) -> Vec { .collect() } +// =========================================================================== +// The pack list (packRef space) +// =========================================================================== + +/// A document's position in the platform total order: `($createdAt, $id)`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CopyKey { + /// Consensus `$createdAt` (ms). + pub created_at: u64, + /// Document `$id`. + pub id: String, +} + +/// One `packManifest` document of a repository, flattened for [`v2_pack_list`]. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PackCopyRow { + /// Document `$id`. + pub id: String, + /// The pack's content hash, hex. + pub pack_hash: String, + /// `kind` (0 git pack, 1 objectLocator, 2 flatIndex). + pub kind: u64, + /// Consensus `$createdAt` (ms). + pub created_at: u64, + /// The uploader's current role ([`RoleOracle::current_role`]); `None` for anyone else. + #[serde(default)] + pub owner_role: Option, + /// `sizeBytes`. + #[serde(default)] + pub size_bytes: u64, + /// `objectCount`. + #[serde(default)] + pub object_count: u64, + /// `chunkCount`. + #[serde(default)] + pub chunk_count: u64, + /// `supersedes` (hex pack hashes). + #[serde(default)] + pub supersedes: Vec, + /// `Some(true)`: this copy's bytes hash to `pack_hash`; `Some(false)`: they do not; + /// `None`: not checked. + #[serde(default)] + pub verified: Option, +} + +/// One pack of [`v2_pack_list`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct V2Pack { + /// The pack's position among the packs of its `kind` (a locator's `packRef`). + pub pack_ref: usize, + /// The pack hash, hex. + pub pack_hash: String, + /// The representative copy's `kind`. + pub kind: u64, + /// The representative copy's `sizeBytes`. + pub size_bytes: u64, + /// The representative copy's `objectCount`. + pub object_count: u64, + /// The representative copy's `chunkCount`. + pub chunk_count: u64, + /// The representative copy's `supersedes`. + pub supersedes: Vec, + /// The earliest `($createdAt, $id)` among every copy of the hash: the pack's position. + pub first: CopyKey, + /// The usable copies, in the order a reader tries them; the representative first. + pub copies: Vec, + /// A pack whose representative copy verified lists this pack in `supersedes`. + pub superseded: bool, +} + +/// Every pack of a repository with its position (`packRef`), from all its `packManifest` +/// copies (`forge-v2.md` §4, vectors `v2_pack_list__*`). Pure; kind-agnostic: pass every +/// copy and select a kind from the output (a copy claiming another kind cannot hide a pack). +/// +/// 1. `as_of` (inclusive) drops copies after it — an older locator indexes only the packs +/// that existed when it was built. +/// 2. Copies are grouped by `pack_hash`. Each group is ranked like [`order_pack_copies`] +/// (maintainer, writer, anyone else; then `($createdAt, $id)`), copies that failed +/// verification are dropped, and the first remaining copy is the **representative**; a +/// hash with no remaining copy is left out. The representative's `kind` and metadata are +/// the pack's, and copies claiming a different kind are dropped from `copies`. +/// 3. `first` is the earliest `($createdAt, $id)` among all the hash's copies (failed and +/// other-kind ones included), so a copy uploaded later — or one ranked higher — never +/// moves a pack. `pack_ref` is the pack's index among the packs of its kind, by `first`. +/// 4. A pack is `superseded` when another listed pack's representative names it in +/// `supersedes` and that representative verified (`Some(true)`); an unchecked claim +/// supersedes nothing. Superseded packs keep their `pack_ref`. +/// +/// Output order: by `kind`, then `pack_ref`. +#[must_use] +pub fn v2_pack_list(copies: &[PackCopyRow], as_of: Option<&CopyKey>) -> Vec { + let key = |c: &PackCopyRow| CopyKey { + created_at: c.created_at, + id: c.id.clone(), + }; + let mut groups: std::collections::BTreeMap<&str, Vec<&PackCopyRow>> = + std::collections::BTreeMap::new(); + for c in copies { + if as_of.is_none_or(|a| key(c) <= *a) { + groups.entry(c.pack_hash.as_str()).or_default().push(c); + } + } + + // (pack, representative verified) per hash that has a usable copy. + let mut packs: Vec<(V2Pack, bool)> = Vec::new(); + for (hash, mut group) in groups { + let first = group + .iter() + .map(|c| key(c)) + .min() + .expect("a group is non-empty"); + group.sort_by(|a, b| { + role_rank(a.owner_role) + .cmp(&role_rank(b.owner_role)) + .then_with(|| a.created_at.cmp(&b.created_at)) + .then_with(|| a.id.cmp(&b.id)) + }); + let usable: Vec<&PackCopyRow> = group + .into_iter() + .filter(|c| c.verified != Some(false)) + .collect(); + let Some(rep) = usable.first().copied() else { + continue; + }; + packs.push(( + V2Pack { + pack_ref: 0, + pack_hash: hash.to_string(), + kind: rep.kind, + size_bytes: rep.size_bytes, + object_count: rep.object_count, + chunk_count: rep.chunk_count, + supersedes: rep.supersedes.clone(), + first, + copies: usable + .iter() + .filter(|c| c.kind == rep.kind) + .map(|c| c.id.clone()) + .collect(), + superseded: false, + }, + rep.verified == Some(true), + )); + } + + let superseded: BTreeSet = packs + .iter() + .filter(|(_, verified)| *verified) + .flat_map(|(p, _)| { + p.supersedes + .iter() + .filter(|s| **s != p.pack_hash) + .cloned() + .collect::>() + }) + .collect(); + let mut out: Vec = packs.into_iter().map(|(p, _)| p).collect(); + out.sort_by(|a, b| a.kind.cmp(&b.kind).then_with(|| a.first.cmp(&b.first))); + let mut kind = None; + let mut index = 0; + for p in &mut out { + if kind != Some(p.kind) { + kind = Some(p.kind); + index = 0; + } + p.pack_ref = index; + index += 1; + p.superseded = superseded.contains(&p.pack_hash); + } + out +} + // =========================================================================== // Approvals // =========================================================================== diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md index fa7fe3ce5..202f4a356 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -112,6 +112,16 @@ Protocol 14 checks references on create and replace only; **a delete is never re **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. +**The pack list** (`FORGE_RULES_V2`: `v2_pack_list`, vectors `v2_pack_list__*`). A locator's `packRef` indexes "the repo's pack list", which must be derived identically by every reader and writer. With several copies per pack it is: + +1. Take every `packManifest` of the repo (all kinds). An older locator bounds the set **as of** its own `($createdAt, $id)`, inclusive. +2. Group the copies by `packHash`. Rank each group like the reader rule (maintainers, writers, everyone else; then `($createdAt, $id)`), drop copies whose bytes failed verification, and call the first remaining copy the **representative**. A hash with no remaining copy is not in the list. The pack's `kind` and metadata (`sizeBytes`, `objectCount`, `chunkCount`, `supersedes`) are the representative's; copies claiming another `kind` are dropped, so a stranger's copy cannot re-label a pack. +3. A pack's position is its **first upload**: the earliest `($createdAt, $id)` among all copies of the hash, failed and other-kind ones included. A later or higher-ranked copy never moves a pack. +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). On forge-v1, where each pack has one copy, it reduces to the v1 rule (live kind-0 packs, oldest first). + `release`, `label`, `webhook`, `checkRun`, `comment`, `review`, `star`, `follow` and `profile` stay deletable. Their resolution is newest-wins or per-author, so a deletion removes only the deleter's own contribution. Residual risk: a revoked maintainer can delete a release they published. Readers fall back to the next-newest release for that tag. The contracts are **not readonly**, so the owner identity can still update them, within the protocol 14 update rules: indexes, `refersTo`/`ownerRefersTo`, `immutable` and `encryptedFor` are all frozen on update, so an update can add optional properties and new document types but cannot loosen an existing gate. **Readonly cannot be switched on later**: a config update to `readonly: true` is refused (`validate_update` v0, "contract can not be changed to readonly"). To make the final mainnet contracts readonly, set `config.readonly` in the JSON when registering them (§8). @@ -170,6 +180,7 @@ Gaps below `base` are never filled. A number above the ceiling cannot be reached | Membership | `RoleOracle::{role_at, member_at, current_role}` | through `approvals__*` | | Numbering | `allocate_number`, `number_ceiling` | `allocate_number__*` | | Pack reader rule (§4) | `order_pack_copies`, `select_pack_copy`, `pack_read_order` | `pack_copies__*` | +| Pack list / `packRef` space (§4) | `v2_pack_list` | `v2_pack_list__*` | | Approvals | `count_approvals` | `approvals__*` | | Plaintext xor `enc` (§5) | `is_well_formed` | `well_formed__*` | | Repository names | `is_valid_repo_name`, `normalize_repo_name` | `repo_name__*` | diff --git a/forge-contracts/scripts/seed-v2-fixture.mjs b/forge-contracts/scripts/seed-v2-fixture.mjs new file mode 100644 index 000000000..9c4b31235 --- /dev/null +++ b/forge-contracts/scripts/seed-v2-fixture.mjs @@ -0,0 +1,411 @@ +#!/usr/bin/env node +// seed-v2-fixture.mjs — seed the forge-v2 read fixture that forge-web's devnet Playwright +// specs and live tests read. +// +// node forge-contracts/scripts/seed-v2-fixture.mjs [--network devnet --devnet-name moutai] +// +// Needs `npm ci` in forge-contracts/sdk-v2 (evo-sdk 4.2, protocol 14) and the devnet test +// identities in ~/.config/dash-forge/test-identities// (OWNER, MAINTAINER, COLLAB, +// CONTRIB). +// +// It writes, as the forge-v2 contracts define them (docs/contracts/forge-v2.md): +// * repo `forge-v2-demo` owned by OWNER; OWNER and MAINTAINER as maintainers, COLLAB as a +// writer; a config protecting refs/heads/main; +// * one deterministic git history (three commits, a feature branch, a tag) packed with git, +// stored on Platform as `chunk` documents behind a kind-0 `packManifest`, plus a kind-1 +// objectLocator over it, so the web app browses it through the published index; +// * refs: main by protectedRefUpdate (two updates), the feature branch by COLLAB's +// refUpdate, the tag by OWNER; +// * issues, a PR still open with an approval, a merged PR, comments, `event`s and an +// `authorEvent`, a star; +// * repo `forge-v2-empty` owned by MAINTAINER, with no refs (the empty-repo state). +// +// The git-remote-dash v2 push path is not there yet (forge-core PR C), which is why the +// pack and the locator are written here directly. The chunk layout is forge-core +// `pack::split` (4900-byte fields, three per chunk); the locator is `pack/locator.rs` +// (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. + +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { loadEvoSdk } from './deploy-v2.mjs'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(HERE, '..'); + +const DEMO = 'forge-v2-demo'; +const EMPTY = 'forge-v2-empty'; +const FIELD_MAX = 4900; +const FIELDS_PER_DOC = 3; +const FANOUT_LEN = 1024; +const ROW_LEN = 36; +const SPAN_SENTINEL = 0xffffffff; +const EVENT = { close: 1, reopen: 2, merge: 3, labelAdd: 4 }; + +const log = (m) => console.error(`${new Date().toISOString().slice(11, 19)} ${m}`); + +function args() { + const out = { network: 'devnet', 'devnet-name': 'moutai' }; + const a = process.argv.slice(2); + for (let i = 0; i < a.length; i += 2) out[a[i].replace(/^--/, '')] = a[i + 1]; + return out; +} + +const sha256 = (bytes) => createHash('sha256').update(bytes).digest(); + +// --------------------------------------------------------------------------- +// The deterministic git history +// --------------------------------------------------------------------------- + +function git(cwd, argv, env = {}) { + return execFileSync('git', argv, { + cwd, + env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', HOME: cwd, ...env }, + maxBuffer: 64 << 20, + }); +} + +function buildHistory() { + const dir = mkdtempSync(join(tmpdir(), 'forge-v2-fixture-')); + git(dir, ['init', '-q', '-b', 'main']); + const commit = (message, when, files) => { + for (const [path, body] of Object.entries(files)) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), body); + } + git(dir, ['add', '-A']); + const date = `${when} +0000`; + git(dir, ['commit', '-q', '-m', message], { + GIT_AUTHOR_NAME: 'Forge Fixture', + GIT_AUTHOR_EMAIL: 'fixture@dash-forge.invalid', + GIT_COMMITTER_NAME: 'Forge Fixture', + GIT_COMMITTER_EMAIL: 'fixture@dash-forge.invalid', + GIT_AUTHOR_DATE: date, + GIT_COMMITTER_DATE: date, + }); + return git(dir, ['rev-parse', 'HEAD']).toString().trim(); + }; + + const c1 = commit('Initial import', '2026-09-01T12:00:00', { + 'README.md': '# forge-v2-demo\n\nThe forge-v2 read fixture: a repository that lives in the shared\n**forge-core** and **forge-collab** contracts (protocol 14).\n\n- `src/` holds the code\n- `lib/` holds helpers\n', + 'src/main.rs': 'fn main() {\n println!("hello from forge-v2");\n}\n', + 'lib/util.ts': 'export function add(a: number, b: number): number {\n return a + b\n}\n', + }); + const c2 = commit('Document the fold rules', '2026-09-02T12:00:00', { + 'docs/rules.md': '# Rules\n\nIssue and PR state is folded from `event` and `authorEvent` documents.\n', + 'src/main.rs': 'fn main() {\n println!("hello from forge-v2");\n println!("reads are proof-checked");\n}\n', + }); + git(dir, ['tag', 'v0.1.0', c1]); + git(dir, ['checkout', '-q', '-b', 'feature/greeting']); + const c3 = commit('Greet by name', '2026-09-03T12:00:00', { + 'src/main.rs': 'fn main() {\n let name = std::env::args().nth(1).unwrap_or("forge".into());\n println!("hello, {name}");\n println!("reads are proof-checked");\n}\n', + }); + git(dir, ['checkout', '-q', 'main']); + return { dir, commits: { c1, c2, c3 } }; +} + +/** `git pack-objects --stdout --all` needs rev-list input; feed it explicitly. */ +function packAll(dir) { + const revs = git(dir, ['rev-list', '--objects', '--all']).toString(); + return execFileSync('git', ['pack-objects', '--stdout', '-q'], { + cwd: dir, + input: revs, + maxBuffer: 64 << 20, + }); +} + +/** Locator rows for one pack (packRef 0), from `git verify-pack -v`. */ +function buildLocator(dir, pack) { + const packPath = join(dir, 'fixture.pack'); + writeFileSync(packPath, pack); + git(dir, ['index-pack', '-o', join(dir, 'fixture.idx'), packPath]); + const out = git(dir, ['verify-pack', '-v', join(dir, 'fixture.idx')]).toString(); + const rows = []; + for (const line of out.split('\n')) { + const m = /^([0-9a-f]{40}) (\w+)\s+(\d+) (\d+) (\d+)(?: (\d+) ([0-9a-f]{40}))?/.exec(line); + if (!m) continue; + rows.push({ oid: m[1], length: Number(m[4]), offset: Number(m[5]), depth: m[6] ? Number(m[6]) : 0 }); + } + rows.sort((a, b) => (a.oid < b.oid ? -1 : a.oid > b.oid ? 1 : 0)); + const bytes = Buffer.alloc(FANOUT_LEN + rows.length * ROW_LEN); + const counts = new Array(256).fill(0); + for (const r of rows) counts[parseInt(r.oid.slice(0, 2), 16)]++; + let cum = 0; + for (let i = 0; i < 256; i++) { + cum += counts[i]; + bytes.writeUInt32BE(cum, i * 4); + } + let at = FANOUT_LEN; + for (const r of rows) { + Buffer.from(r.oid, 'hex').copy(bytes, at); + bytes.writeUInt16BE(0, at + 20); + bytes.writeUIntBE(r.offset, at + 22, 5); + bytes.writeUInt32BE(r.length, at + 27); + bytes.writeUInt32BE(SPAN_SENTINEL, at + 31); + bytes[at + 35] = Math.min(r.depth, 255); + at += ROW_LEN; + } + return { bytes, objectCount: rows.length }; +} + +/** forge-core `pack::split`: fill 4900-byte fields, three per chunk. */ +function split(data) { + const chunks = []; + for (let at = 0; at < data.length; at += FIELD_MAX * FIELDS_PER_DOC) { + const doc = data.subarray(at, at + FIELD_MAX * FIELDS_PER_DOC); + const fields = []; + for (let f = 0; f < doc.length; f += FIELD_MAX) fields.push(doc.subarray(f, f + FIELD_MAX)); + chunks.push(fields); + } + return chunks; +} + +// --------------------------------------------------------------------------- +// Platform writes +// --------------------------------------------------------------------------- + +async function main() { + const a = args(); + const network = a.network; + const devnetName = network === 'devnet' ? a['devnet-name'] : null; + const key = devnetName ? `devnet-${devnetName}` : network; + const dep = JSON.parse(readFileSync(join(ROOT, 'deployments', `${key}.json`), 'utf8')); + const core = dep.v2?.forgeCore?.contractId; + const collab = dep.v2?.forgeCollab?.contractId; + if (!core || !collab) throw new Error(`no forge-v2 deployment recorded for ${key}`); + + const evo = await loadEvoSdk(); + const { EvoSDK, Document, IdentityPublicKey, IdentitySigner, PrivateKey } = evo; + const sdk = new EvoSDK({ + network, + trusted: true, + ...(devnetName ? { devnetName } : {}), + ...(dep.dapiAddresses ? { addresses: dep.dapiAddresses } : {}), + settings: { timeoutMs: 30000 }, + }); + await sdk.connect(); + + const idDir = join(homedir(), '.config/dash-forge/test-identities', key); + const load = (name) => { + const rec = JSON.parse(readFileSync(join(idDir, `${name}.identity.json`), 'utf8')); + const k = rec.identityKeys.find((x) => x.purpose === 'AUTHENTICATION' && x.securityLevel === 'HIGH'); + const identityKey = new IdentityPublicKey({ + keyId: k.id, + purpose: k.purpose, + securityLevel: k.securityLevel, + keyType: k.keyType, + isReadOnly: false, + data: Buffer.from(k.publicKeyHex, 'hex'), + }); + const signer = new IdentitySigner(); + signer.addKey(PrivateKey.fromWIF(k.privateKeyWif)); + return { name, id: rec.identityId, identityKey, signer }; + }; + const OWNER = load('OWNER'); + const MAINTAINER = load('MAINTAINER'); + const COLLAB = load('COLLAB'); + const CONTRIB = load('CONTRIB'); + + const statePath = join(homedir(), '.cache/dash-forge', `seed-v2-${key}.json`); + mkdirSync(dirname(statePath), { recursive: true }); + const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : {}; + const save = () => writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`); + + const b58 = (s) => Buffer.from(evo.Identifier.fromBase58(s).toBytes()); + const version = sdk.version(); + + /** Create one document (once: the step name is recorded with its id). */ + async function create(step, who, contractId, documentTypeName, data) { + if (state[step]) return state[step]; + const base = new Document({ properties: {}, documentTypeName, dataContractId: contractId, ownerId: who.id }); + const document = Document.fromObject({ ...base.toObject(), ...data }, version); + const created = await sdk.documents.create({ document, identityKey: who.identityKey, signer: who.signer }); + const id = created.id.toBase58(); + state[step] = id; + save(); + log(`${step}: ${documentTypeName} ${id} (${who.name})`); + return id; + } + + // --- repos, membership, config ----------------------------------------------------- + const repoId = await create('repo', OWNER, core, 'repo', { + name: DEMO, + visibility: 'public', + displayName: 'forge-v2 demo', + description: 'The forge-v2 read fixture: code, issues and pull requests in the shared contracts.', + defaultBranch: 'main', + topics: ['fixture', 'forge-v2'], + }); + const R = b58(repoId); + await create('maintainer:owner', OWNER, core, 'maintainer', { repoId: R, memberId: b58(OWNER.id) }); + await create('config', OWNER, core, 'config', { + repoId: R, + defaultBranch: 'main', + protectedPatterns: ['refs/heads/main'], + backend: { mode: 0 }, + }); + await create('maintainer:maintainer', OWNER, core, 'maintainer', { repoId: R, memberId: b58(MAINTAINER.id) }); + await create('writer:collab', OWNER, core, 'writer', { repoId: R, memberId: b58(COLLAB.id) }); + + const emptyId = await create('repo:empty', MAINTAINER, core, 'repo', { + name: EMPTY, + visibility: 'public', + description: 'A forge-v2 repository with nothing pushed yet.', + }); + const E = b58(emptyId); + await create('empty:maintainer', MAINTAINER, core, 'maintainer', { repoId: E, memberId: b58(MAINTAINER.id) }); + await create('empty:config', MAINTAINER, core, 'config', { repoId: E, defaultBranch: 'main' }); + + // --- content: pack + locator on Platform -------------------------------------------- + const { dir, commits } = buildHistory(); + if (state.commits && JSON.stringify(state.commits) !== JSON.stringify(commits)) { + throw new Error(`the fixture history changed (${JSON.stringify(commits)} vs recorded ${JSON.stringify(state.commits)})`); + } + state.commits = commits; + save(); + const pack = packAll(dir); + const packHash = sha256(pack); + const locator = buildLocator(dir, pack); + const locatorHash = sha256(locator.bytes); + // Pack bytes depend on the git and zlib versions: a rerun must not write the rest of an + // interrupted artifact under a different hash than its first chunks. + const hashes = { pack: packHash.toString('hex'), locator: locatorHash.toString('hex') }; + if (state.hashes && JSON.stringify(state.hashes) !== JSON.stringify(hashes)) { + throw new Error(`the packed bytes changed (${JSON.stringify(hashes)} vs recorded ${JSON.stringify(state.hashes)}); seed from scratch`); + } + state.hashes = hashes; + save(); + + async function storeArtifact(label, bytes, hash, kind, objectCount) { + const chunks = split(bytes); + for (let seq = 0; seq < chunks.length; seq++) { + const data = { repoId: R, packHash: hash, seq }; + chunks[seq].forEach((field, i) => { + data[`d${i}`] = Uint8Array.from(field); + }); + await create(`${label}:chunk:${seq}`, OWNER, core, 'chunk', data); + } + return create(`${label}:manifest`, OWNER, core, 'packManifest', { + repoId: R, + packHash: hash, + kind, + sizeBytes: bytes.length, + objectCount, + chunkCount: chunks.length, + storage: 0, + offsetIndexParts: 0, + }); + } + await storeArtifact('pack', pack, packHash, 0, locator.objectCount); + await storeArtifact('locator', locator.bytes, locatorHash, 1, locator.objectCount); + + // --- refs --------------------------------------------------------------------------- + const oid = (hex) => Buffer.from(hex, 'hex'); + const refHash = (name) => sha256(Buffer.from(name)); + await create('ref:main:1', OWNER, core, 'protectedRefUpdate', { + repoId: R, refNameHash: refHash('refs/heads/main'), refName: 'refs/heads/main', newOid: oid(commits.c1), + }); + await create('ref:main:2', MAINTAINER, core, 'protectedRefUpdate', { + repoId: R, refNameHash: refHash('refs/heads/main'), refName: 'refs/heads/main', prevOid: oid(commits.c1), newOid: oid(commits.c2), + }); + await create('ref:feature', COLLAB, core, 'refUpdate', { + repoId: R, refNameHash: refHash('refs/heads/feature/greeting'), refName: 'refs/heads/feature/greeting', newOid: oid(commits.c3), + }); + await create('ref:tag', OWNER, core, 'refUpdate', { + repoId: R, refNameHash: refHash('refs/tags/v0.1.0'), refName: 'refs/tags/v0.1.0', newOid: oid(commits.c1), + }); + + // --- issues ------------------------------------------------------------------------- + const issue = (n, who, title, body) => + create(`issue:${n}`, who, collab, 'issue', { repoId: R, number: n, title, body }); + const i1 = await issue(1, CONTRIB, 'README should explain the event split', 'The README does not say why `authorEvent` is its own type.'); + const i2 = await issue(2, CONTRIB, 'Duplicate of #1', 'Opened twice by mistake.'); + const i3 = await issue(3, CONTRIB, 'Add a rules page', 'A page documenting the fold would help.'); + const ev = (step, who, type, targetId, targetNumber, kind, extra = {}) => + create(step, who, collab, type, { repoId: R, targetId: b58(targetId), targetNumber, kind, ...extra }); + await ev('issue:2:author-close', CONTRIB, 'authorEvent', i2, 2, EVENT.close); + await ev('issue:3:label', MAINTAINER, 'event', i3, 3, EVENT.labelAdd, { value: 'docs' }); + await ev('issue:3:close', MAINTAINER, 'event', i3, 3, EVENT.close); + await ev('issue:1:label', COLLAB, 'event', i1, 1, EVENT.labelAdd, { value: 'question' }); + const comment = (step, who, targetId, body) => + create(step, who, collab, 'comment', { repoId: R, targetId: b58(targetId), body }); + await comment('issue:1:comment:1', MAINTAINER, i1, 'Good point: the split is in docs/contracts/forge-v2.md §3.'); + await comment('issue:3:comment:1', MAINTAINER, i3, 'Done in docs/rules.md; closing.'); + + // --- pull requests ------------------------------------------------------------------ + const patch = (n, who, title, body, headOid, sourceRef) => + create(`patch:${n}`, who, collab, 'patch', { + repoId: R, + number: n, + title, + body, + baseRefNameHash: refHash('refs/heads/main'), + baseRefName: 'refs/heads/main', + sourceRepoId: R, + sourceRefNameHash: refHash(sourceRef), + sourceRefName: sourceRef, + headOid: oid(headOid), + }); + const p1 = await patch(1, COLLAB, 'Greet by name', 'Reads the name from argv.', commits.c3, 'refs/heads/feature/greeting'); + const p2 = await patch(2, MAINTAINER, 'Document the fold rules', 'Adds docs/rules.md.', commits.c2, 'refs/heads/main'); + await create('patch:1:review', MAINTAINER, collab, 'review', { + repoId: R, patchId: b58(p1), verdict: 1, commitOid: oid(commits.c3), body: 'Looks good.', + }); + await comment('patch:1:comment:1', OWNER, p1, 'Nice. Waiting on one more review.'); + await ev('patch:2:merge', OWNER, 'event', p2, 2, EVENT.merge, { oid: oid(commits.c2) }); + + // --- social --------------------------------------------------------------------------- + // `star` is indexOnly: evo-sdk 4.2's strict wait refuses that transition family after it + // lands, so the star is confirmed by a count read instead. + if (!state['star:contrib']) { + const starCount = async () => { + const counts = await sdk.documents.count({ + dataContractId: collab, + documentTypeName: 'star', + where: [['repoId', '==', repoId]], + }); + let n = 0n; + for (const v of counts.values()) n += v; + return n; + }; + if ((await starCount()) === 0n) { + const base = new Document({ properties: {}, documentTypeName: 'star', dataContractId: collab, ownerId: CONTRIB.id }); + const document = Document.fromObject({ ...base.toObject(), repoId: R }, version); + try { + await sdk.documents.create({ document, identityKey: CONTRIB.identityKey, signer: CONTRIB.signer }); + } catch (e) { + if (!/VerifiedDocuments snapshot/.test(String(e?.message ?? e))) throw e; + } + for (let i = 0; i < 10 && (await starCount()) === 0n; i++) await new Promise((r) => setTimeout(r, 2000)); + if ((await starCount()) === 0n) throw new Error('the star did not land'); + } + state['star:contrib'] = 'indexOnly'; + save(); + log('star:contrib'); + } + + const summary = { + network: key, + forgeCore: core, + forgeCollab: collab, + demo: { owner: OWNER.id, name: DEMO, repoId }, + empty: { owner: MAINTAINER.id, name: EMPTY, repoId: emptyId }, + commits, + packHash: packHash.toString('hex'), + locatorHash: locatorHash.toString('hex'), + }; + console.log(JSON.stringify(summary, null, 2)); +} + +main().catch((e) => { + console.error(e?.stack ?? e?.message ?? String(e)); + process.exit(1); +}); diff --git a/forge-contracts/vectors/v2_pack_list__all_copies_failed_pack_dropped.json b/forge-contracts/vectors/v2_pack_list__all_copies_failed_pack_dropped.json new file mode 100644 index 000000000..195bfb4a6 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__all_copies_failed_pack_dropped.json @@ -0,0 +1,89 @@ +{ + "name": "all_copies_failed_pack_dropped", + "description": "Every copy of P2 failed verification: P2 is left out, and P3 takes the next packRef.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "a", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer", + "verified": true + }, + { + "id": "b", + "packHash": "P2", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer", + "verified": false + }, + { + "id": "c", + "packHash": "P2", + "kind": 0, + "createdAt": 25, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer", + "verified": false + }, + { + "id": "d", + "packHash": "P3", + "kind": 0, + "createdAt": 30, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "a" + }, + "copies": [ + "a" + ], + "superseded": false + }, + { + "packRef": 1, + "packHash": "P3", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 30, + "id": "d" + }, + "copies": [ + "d" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__as_of_cut_is_inclusive.json b/forge-contracts/vectors/v2_pack_list__as_of_cut_is_inclusive.json new file mode 100644 index 000000000..797ace833 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__as_of_cut_is_inclusive.json @@ -0,0 +1,90 @@ +{ + "name": "as_of_cut_is_inclusive", + "description": "asOf (20, \"b\") keeps copies at or before it: P2 (exactly at the bound) is in, P3 is out, and the later copy of P1 is not counted.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "a", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "b", + "packHash": "P2", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "c", + "packHash": "P3", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "z", + "packHash": "P1", + "kind": 0, + "createdAt": 50, + "sizeBytes": 500, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer" + } + ], + "asOf": { + "createdAt": 20, + "id": "b" + } + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "a" + }, + "copies": [ + "a" + ], + "superseded": false + }, + { + "packRef": 1, + "packHash": "P2", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 20, + "id": "b" + }, + "copies": [ + "b" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__failed_copy_skipped_for_representative.json b/forge-contracts/vectors/v2_pack_list__failed_copy_skipped_for_representative.json new file mode 100644 index 000000000..c5e2862e9 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__failed_copy_skipped_for_representative.json @@ -0,0 +1,50 @@ +{ + "name": "failed_copy_skipped_for_representative", + "description": "The maintainer's copy failed verification: the writer's copy represents the pack; the failed copy is not in `copies` but still sets `first`.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "m1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 999, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer", + "verified": false + }, + { + "id": "w1", + "packHash": "P1", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "m1" + }, + "copies": [ + "w1" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__interleaved_kinds_keep_kind0_refs_contiguous.json b/forge-contracts/vectors/v2_pack_list__interleaved_kinds_keep_kind0_refs_contiguous.json new file mode 100644 index 000000000..8e0dfd062 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__interleaved_kinds_keep_kind0_refs_contiguous.json @@ -0,0 +1,147 @@ +{ + "name": "interleaved_kinds_keep_kind0_refs_contiguous", + "description": "Kind-0 packs and kind-1 fragments interleaved in time: kind-0 packRefs are 0..n with no gaps for the fragments, and fragments number separately.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "p1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "l1", + "packHash": "L1", + "kind": 1, + "createdAt": 11, + "sizeBytes": 36, + "objectCount": 2, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "p2", + "packHash": "P2", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "l2", + "packHash": "L2", + "kind": 1, + "createdAt": 21, + "sizeBytes": 36, + "objectCount": 2, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "p3", + "packHash": "P3", + "kind": 0, + "createdAt": 30, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "p1" + }, + "copies": [ + "p1" + ], + "superseded": false + }, + { + "packRef": 1, + "packHash": "P2", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 20, + "id": "p2" + }, + "copies": [ + "p2" + ], + "superseded": false + }, + { + "packRef": 2, + "packHash": "P3", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 30, + "id": "p3" + }, + "copies": [ + "p3" + ], + "superseded": false + }, + { + "packRef": 0, + "packHash": "L1", + "kind": 1, + "sizeBytes": 36, + "objectCount": 2, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 11, + "id": "l1" + }, + "copies": [ + "l1" + ], + "superseded": false + }, + { + "packRef": 1, + "packHash": "L2", + "kind": 1, + "sizeBytes": 36, + "objectCount": 2, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 21, + "id": "l2" + }, + "copies": [ + "l2" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__kind_disagreement_dropped.json b/forge-contracts/vectors/v2_pack_list__kind_disagreement_dropped.json new file mode 100644 index 000000000..19849a36b --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__kind_disagreement_dropped.json @@ -0,0 +1,59 @@ +{ + "name": "kind_disagreement_dropped", + "description": "Copies of one hash disagree on kind: the representative's kind wins and the disagreeing copy is left out of `copies`; it still counts for `first`.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "x1", + "packHash": "P1", + "kind": 1, + "createdAt": 5, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1 + }, + { + "id": "m1", + "packHash": "P1", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer" + }, + { + "id": "w1", + "packHash": "P1", + "kind": 0, + "createdAt": 30, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 5, + "id": "x1" + }, + "copies": [ + "m1", + "w1" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__maintainer_copy_beats_older_writer_copy.json b/forge-contracts/vectors/v2_pack_list__maintainer_copy_beats_older_writer_copy.json new file mode 100644 index 000000000..744846f40 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__maintainer_copy_beats_older_writer_copy.json @@ -0,0 +1,50 @@ +{ + "name": "maintainer_copy_beats_older_writer_copy", + "description": "Two uploads of one pack: the maintainer's later copy is the representative (its metadata wins) and is tried first; the position is the writer's earlier upload.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "w1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 111, + "objectCount": 7, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "m1", + "packHash": "P1", + "kind": 0, + "createdAt": 20, + "sizeBytes": 222, + "objectCount": 9, + "chunkCount": 1, + "ownerRole": "maintainer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 222, + "objectCount": 9, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "w1" + }, + "copies": [ + "m1", + "w1" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__mixed_kind_claim_cannot_hide_a_pack.json b/forge-contracts/vectors/v2_pack_list__mixed_kind_claim_cannot_hide_a_pack.json new file mode 100644 index 000000000..fa14be65c --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__mixed_kind_claim_cannot_hide_a_pack.json @@ -0,0 +1,48 @@ +{ + "name": "mixed_kind_claim_cannot_hide_a_pack", + "description": "A non-member's copy claims kind 1 for a git pack a writer uploaded as kind 0: the writer outranks it, so the pack stays a kind-0 pack.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "x1", + "packHash": "P1", + "kind": 1, + "createdAt": 5, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1 + }, + { + "id": "w1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 5, + "id": "x1" + }, + "copies": [ + "w1" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__position_stable_when_a_later_copy_ranks_higher.json b/forge-contracts/vectors/v2_pack_list__position_stable_when_a_later_copy_ranks_higher.json new file mode 100644 index 000000000..85f695e24 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__position_stable_when_a_later_copy_ranks_higher.json @@ -0,0 +1,77 @@ +{ + "name": "position_stable_when_a_later_copy_ranks_higher", + "description": "A maintainer re-uploads P1 after P2 landed: its copy becomes P1's representative, but P1 keeps packRef 0 because its first upload is still the earliest.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "w1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "w2", + "packHash": "P2", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "m1", + "packHash": "P1", + "kind": 0, + "createdAt": 30, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "w1" + }, + "copies": [ + "m1", + "w1" + ], + "superseded": false + }, + { + "packRef": 1, + "packHash": "P2", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 20, + "id": "w2" + }, + "copies": [ + "w2" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__self_supersede_ignored.json b/forge-contracts/vectors/v2_pack_list__self_supersede_ignored.json new file mode 100644 index 000000000..c08976c0e --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__self_supersede_ignored.json @@ -0,0 +1,45 @@ +{ + "name": "self_supersede_ignored", + "description": "A verified pack listing its own hash in supersedes does not supersede itself.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "a", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer", + "verified": true, + "supersedes": [ + "P1" + ] + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [ + "P1" + ], + "first": { + "createdAt": 10, + "id": "a" + }, + "copies": [ + "a" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__single_copy.json b/forge-contracts/vectors/v2_pack_list__single_copy.json new file mode 100644 index 000000000..8118e94d7 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__single_copy.json @@ -0,0 +1,39 @@ +{ + "name": "single_copy", + "description": "One manifest: one pack at packRef 0, its only copy is the representative.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "m1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "m1" + }, + "copies": [ + "m1" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__supersedes_only_from_a_verified_representative.json b/forge-contracts/vectors/v2_pack_list__supersedes_only_from_a_verified_representative.json new file mode 100644 index 000000000..bc57fcff3 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__supersedes_only_from_a_verified_representative.json @@ -0,0 +1,131 @@ +{ + "name": "supersedes_only_from_a_verified_representative", + "description": "C1 verified and supersedes P1; U1 is unchecked and claims to supersede P2: P1 is superseded, P2 is not. Superseded packs keep their packRef.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "a", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "b", + "packHash": "P2", + "kind": 0, + "createdAt": 20, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "c", + "packHash": "C1", + "kind": 0, + "createdAt": 30, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer", + "verified": true, + "supersedes": [ + "P1" + ] + }, + { + "id": "u", + "packHash": "U1", + "kind": 0, + "createdAt": 40, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer", + "supersedes": [ + "P2" + ] + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "a" + }, + "copies": [ + "a" + ], + "superseded": true + }, + { + "packRef": 1, + "packHash": "P2", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 20, + "id": "b" + }, + "copies": [ + "b" + ], + "superseded": false + }, + { + "packRef": 2, + "packHash": "C1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [ + "P1" + ], + "first": { + "createdAt": 30, + "id": "c" + }, + "copies": [ + "c" + ], + "superseded": false + }, + { + "packRef": 3, + "packHash": "U1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [ + "P2" + ], + "first": { + "createdAt": 40, + "id": "u" + }, + "copies": [ + "u" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__tie_break_by_id.json b/forge-contracts/vectors/v2_pack_list__tie_break_by_id.json new file mode 100644 index 000000000..59069a67e --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__tie_break_by_id.json @@ -0,0 +1,66 @@ +{ + "name": "tie_break_by_id", + "description": "Two packs uploaded at the same time are positioned by document $id.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "zz", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + }, + { + "id": "aa", + "packHash": "P2", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "writer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P2", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "aa" + }, + "copies": [ + "aa" + ], + "superseded": false + }, + { + "packRef": 1, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "zz" + }, + "copies": [ + "zz" + ], + "superseded": false + } + ] +} diff --git a/forge-contracts/vectors/v2_pack_list__two_hashes_of_different_kinds.json b/forge-contracts/vectors/v2_pack_list__two_hashes_of_different_kinds.json new file mode 100644 index 000000000..f52fc9f09 --- /dev/null +++ b/forge-contracts/vectors/v2_pack_list__two_hashes_of_different_kinds.json @@ -0,0 +1,66 @@ +{ + "name": "two_hashes_of_different_kinds", + "description": "A git pack and a locator: each is packRef 0 within its own kind; output is by kind, then packRef.", + "case": "v2_pack_list", + "rules": "v2", + "input": { + "copies": [ + { + "id": "l1", + "packHash": "L1", + "kind": 1, + "createdAt": 5, + "sizeBytes": 36, + "objectCount": 2, + "chunkCount": 1, + "ownerRole": "maintainer" + }, + { + "id": "p1", + "packHash": "P1", + "kind": 0, + "createdAt": 10, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "ownerRole": "maintainer" + } + ] + }, + "expected": [ + { + "packRef": 0, + "packHash": "P1", + "kind": 0, + "sizeBytes": 100, + "objectCount": 5, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 10, + "id": "p1" + }, + "copies": [ + "p1" + ], + "superseded": false + }, + { + "packRef": 0, + "packHash": "L1", + "kind": 1, + "sizeBytes": 36, + "objectCount": 2, + "chunkCount": 1, + "supersedes": [], + "first": { + "createdAt": 5, + "id": "l1" + }, + "copies": [ + "l1" + ], + "superseded": false + } + ] +} diff --git a/forge-web/app/new/page.tsx b/forge-web/app/new/page.tsx index 6a1c2e0b7..e0946bd8b 100644 --- a/forge-web/app/new/page.tsx +++ b/forge-web/app/new/page.tsx @@ -8,14 +8,15 @@ import { useMemo, useState } from 'react' import { useRouter } from 'next/navigation' -import { GitBranch, Hammer, Lock } from 'lucide-react' +import { GitBranch, Hammer, Lock, Terminal } 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, isRegistryDeployed } from '@/components/ui/network-badge' +import { NotDeployedState, isRegistryDeployed, isV2Deployed } from '@/components/ui/network-badge' +import { ACTIVE_NETWORK } from '@/lib/constants' import { useAuth } from '@/contexts/auth-context' import { useUiStore } from '@/hooks/use-ui-store' import { useSdk } from '@/hooks/use-sdk' @@ -70,7 +71,15 @@ export default function NewRepoPage(): JSX.Element { if (!isRegistryDeployed()) { return ( - + {isV2Deployed() ? ( + .`} + /> + ) : ( + + )} ) } diff --git a/forge-web/app/page.tsx b/forge-web/app/page.tsx index 88e29d3b2..0570dfa39 100644 --- a/forge-web/app/page.tsx +++ b/forge-web/app/page.tsx @@ -15,20 +15,28 @@ 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, isRegistryDeployed } from '@/components/ui/network-badge' +import { + NotDeployedState, + V2NotDeployedNote, + isForgeDeployed, + isRegistryDeployed, + isV2Deployed, +} from '@/components/ui/network-badge' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' -import { connectionTrust, deriveConnectionTrust, listRecentRepos } from '@/lib/view' +import { connectionTrust, deriveConnectionTrust, listRecentRepos, type DiscoveredRepo } from '@/lib/view' export default function LandingPage(): JSX.Element { const { sdk, ready, trusted, error: sdkError, network } = useSdk() const proofs = deriveConnectionTrust(network, connectionTrust(ready, trusted)) - const deployed = isRegistryDeployed() + 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 ( @@ -71,7 +79,7 @@ export default function LandingPage(): JSX.Element {

Recent repos

- {feed.loading ? : null} + {feed.loading ? : null}
{!deployed ? ( @@ -80,11 +88,11 @@ export default function LandingPage(): JSX.Element { ) : feed.error ? ( - ) : feed.data && feed.data.length === 0 ? ( + ) : feed.data && total === 0 ? (

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

diff --git a/forge-web/components/repo/hidden-note.tsx b/forge-web/components/repo/hidden-note.tsx new file mode 100644 index 000000000..bddca0532 --- /dev/null +++ b/forge-web/components/repo/hidden-note.tsx @@ -0,0 +1,15 @@ +/** + * The line a list shows when it skipped documents: not well-formed for the repo (plaintext in + * a private repo, ciphertext in a public one) or a stranger's ciphertext in a private repo + * (`forge-v2.md` §5). Never silent — a list that quietly shrinks looks like an empty repo. + */ +export function HiddenNote({ hidden, what }: { hidden: number; what: string }): JSX.Element | null { + if (hidden <= 0) return null + return ( +

+ {hidden} newer {what} + {hidden === 1 ? ' was' : ' were'} hidden: not readable in this repo (malformed, or encrypted + by someone who is not a member). +

+ ) +} diff --git a/forge-web/components/repo/issue-content.tsx b/forge-web/components/repo/issue-content.tsx index e6109f8a1..705464e03 100644 --- a/forge-web/components/repo/issue-content.tsx +++ b/forge-web/components/repo/issue-content.tsx @@ -11,8 +11,8 @@ import { useState } from 'react' import { CheckCircle2, CircleDot } from 'lucide-react' import type { RepoHome, IssueThread } from '@/lib/view' -import { loadIssueThread, timeAgo } from '@/lib/view' -import { closeTarget, createComment, readViewerHoldings, reopenTarget } from '@/lib/repo' +import { aclName, loadIssueThread, timeAgo } from '@/lib/view' +import { closeTarget, createComment, readViewerPermissions, reopenTarget, repoContractIds, repoKey } from '@/lib/repo' import type { Holdings } from '@/lib/rules' import { previewDocumentCreate } from '@/lib/sdk' import { useSdk } from '@/hooks/use-sdk' @@ -27,6 +27,7 @@ import { Button } from '@/components/ui/button' import { Textarea } from '@/components/ui/input' import { CostPreview } from '@/components/ui/cost-preview' import { EmptyState, ErrorState, LoadingBlock } from '@/components/ui/states' +import { V2WritesNote } from '@/components/repo/v2-writes-note' import { errorMessage } from '@/lib/utils' export function IssueContent({ @@ -36,19 +37,22 @@ export function IssueContent({ home: RepoHome number: number }): JSX.Element { - const { sdk, ready, network } = useSdk([home.repo.contractId]) + const { sdk, ready, network } = useSdk(repoContractIds(home.repo)) + // The web app writes to v1 repos only; forge-v2 writes are the next step (`V2WritesNote`). + const v1 = home.repo.kind === 'v1' ? home.repo : null const { identity, signer } = useAuth() const openLogin = useUiStore((s) => s.openLogin) const { data, loading, error, reload } = useAsync( () => loadIssueThread(sdk!, home.repo, number), - [ready, home.repo.contractId, number], + [ready, repoKey(home.repo), number], { enabled: ready && sdk !== null && Number.isFinite(number) }, ) + // v1: WRITE/MAINTAIN token holdings; forge-v2: a current maintainer/writer document. const holdings = useAsync( - () => readViewerHoldings(sdk!, home.repo, identity!, network), - [ready, home.repo.contractId, identity ?? '', network], + () => readViewerPermissions(sdk!, home.repo, identity!, network), + [ready, repoKey(home.repo), identity ?? '', network], { enabled: ready && sdk !== null && identity !== null }, ) @@ -70,7 +74,7 @@ export function IssueContent({ // rather than silently withholding the control (the PR page does the same for merge). const toggleHint = !canToggle && identity !== null && holdings.settled && holdings.data === null - ? "Couldn't read this repo's token history, so close/reopen permission is unknown." + ? `Couldn't read this repo's ${aclName(home.repo.kind)}, so close/reopen permission is unknown.` : null const postComment = async (): Promise => { @@ -78,11 +82,11 @@ export function IssueContent({ openLogin() return } - if (!sdk || comment.trim() === '') return + if (!sdk || !v1 || comment.trim() === '') return setPosting(true) setCommentError(null) try { - await createComment(sdk, signer, home.repo, { targetId: issue.id, body: comment.trim() }) + await createComment(sdk, signer, v1, { targetId: issue.id, body: comment.trim() }) setComment('') reload() } catch (e) { @@ -93,9 +97,9 @@ export function IssueContent({ } const toggleState = async (): Promise => { - if (!sdk || !signer) return - if (open) await closeTarget(sdk, signer, home.repo, issue.id) - else await reopenTarget(sdk, signer, home.repo, issue.id) + if (!sdk || !signer || !v1) return + if (open) await closeTarget(sdk, signer, v1, issue.id) + else await reopenTarget(sdk, signer, v1, issue.id) reload() } @@ -142,15 +146,16 @@ export function IssueContent({
{canToggle ? ( - ) : null} -
+ {!v1 ? : null} {toggleHint !== null ? (

{toggleHint}

) : null} diff --git a/forge-web/components/repo/issues-content.tsx b/forge-web/components/repo/issues-content.tsx index 58076c752..5607a6458 100644 --- a/forge-web/components/repo/issues-content.tsx +++ b/forge-web/components/repo/issues-content.tsx @@ -10,8 +10,8 @@ import { useMemo, useState } from 'react' import Link from 'next/link' import { CircleDot, CheckCircle2, MessageSquarePlus } from 'lucide-react' import type { RepoHome } from '@/lib/view' -import type { IssueView } from '@/lib/repo' -import { createIssue, listIssues } from '@/lib/repo' +import type { IssueView, Listed } from '@/lib/repo' +import { createIssue, listIssues, repoContractIds, repoKey } from '@/lib/repo' import { previewDocumentCreate } from '@/lib/sdk' import { timeAgo } from '@/lib/view' import { useSdk } from '@/hooks/use-sdk' @@ -24,6 +24,8 @@ import { Dialog } from '@/components/ui/dialog' import { Field, Input, Textarea } from '@/components/ui/input' import { CostPreview } from '@/components/ui/cost-preview' import { EmptyState, ErrorState, LoadingBlock } from '@/components/ui/states' +import { V2WritesNote } from '@/components/repo/v2-writes-note' +import { HiddenNote } from '@/components/repo/hidden-note' import type { RepoAddress } from '@/hooks/use-query-param' import { repoHref } from '@/hooks/use-query-param' import { cn, errorMessage } from '@/lib/utils' @@ -31,13 +33,13 @@ import { cn, errorMessage } from '@/lib/utils' type Filter = 'open' | 'closed' | 'all' export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddress }): JSX.Element { - const { sdk, ready } = useSdk([home.repo.contractId]) + const { sdk, ready } = useSdk(repoContractIds(home.repo)) const [filter, setFilter] = useState('open') const [composing, setComposing] = useState(false) - const { data, loading, error, reload } = useAsync( + const { data, loading, error, reload } = useAsync>( () => listIssues(sdk!, home.repo, undefined, 100), - [ready, home.repo.contractId], + [ready, repoKey(home.repo)], { enabled: ready && sdk !== null }, ) @@ -123,6 +125,8 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres )} +