gitoria
All repositories: gitoria
53.0 KB
import { requiredPort, requiredPortRange } from './gate-ports.mjs';// tests/repo-rename.mjs — Live owner rename, stable repo identity, old URLs and display names.// Isolated storage, ident, real Git transport and keyboard forms.// GITORIA_RENAME_PORT (app; +1 receiver, +2 ident), GITORIA_GATE_CHROME (browser range).// HL_CDP_URL optionally attaches to the shared Chrome under its lock, with before/after target evidence.import { spawn, execFileSync } from 'node:child_process';import { request, createServer } from 'node:http';import { mkdirSync, rmSync, writeFileSync, existsSync, lstatSync, readlinkSync, realpathSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';import { launchBrowser } from './cdp.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const CHROME = requiredPortRange('GITORIA_GATE_CHROME');const HOSTNAME = process.env.HL_CDP_URL ? 'w54.localhost' : 'localhost';const PORT = requiredPort('GITORIA_RENAME_PORT'), RPORT = PORT + 1, IDENT_PORT = process.env.GITORIA_RENAME_IDENT_PORT ? requiredPort('GITORIA_RENAME_IDENT_PORT') : PORT + 2;const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));const STORE = join(APP, '.scratch/repo-rename-store');const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));let passes = 0, failures = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };const got = [];const receiver = createServer((req, res) => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => { got.push({ path: req.url, headers: req.headers, body: Buffer.concat(c).toString('utf8') }); if (req.url === '/api/connect/exchange') { res.setHeader('content-type', 'application/json'); res.end(J({ key: 'tktc_w53_gate', project: 'w53', title: 'W53 tickets', api: `http://127.0.0.1:${RPORT}/api/projects/w53` })); return; } res.statusCode = 204; res.end(); }); });await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));function raw(method, path, { host = `${HOSTNAME}:${PORT}`, headers = {}, body = null, cookie = null } = {}) {return new Promise((res, rej) => {const h = { host, ...headers }; if (cookie) h.cookie = cookie;if (body !== null) h['content-length'] = Buffer.byteLength(body);const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}const get = (path, o = {}) => raw('GET', path, o);const errOf = (r) => { try { return JSON.parse(r.body).error; } catch { return {}; } };let server = null, log = '';async function up() { for (let i = 0; i < 960; i++) { if (server.exitCode !== null || server.signalCode !== null) throw new Error('gitoria exited: ' + log); try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }const stop = async () => { if (server) { const p = server; server = null; if (p.exitCode === null && p.signalCode === null) { p.kill(); await new Promise(r => p.once('exit', r)); } } };let ident;let browser, pg, mirror, beforePages, chromeLock, anon, bobPage;try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');const BASE = `http://${HOSTNAME}:${PORT}`;const app = await ident.registerApp(alice, 'gitoria (member-merge gate)', [BASE]);const GIT = join(STORE, 'git');const env = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: GIT, IDENT_URL: process.env.HL_CDP_URL ? `http://ident.${HOSTNAME}:${IDENT_PORT}` : ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: BASE, GITORIA_SSH_SECRET: 'sshsecret-mm-gate', GITORIA_TICKETS_URL: `http://127.0.0.1:${RPORT}`, GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', ...env } });writeFileSync(join(STORE, 'pids.txt'), `gitoria ${server.pid}\nident ${ident.proc.pid}\n`);server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);await up();const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const login = async (who) => { const ck = cookieOf(await get('/')); const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(who, app, BASE) + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; };let n = 0;const face = async (who, event, payload) => { const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) }); let j = null; try { j = JSON.parse(r.body); } catch {} return j && j.value; };const A = await login(alice), B = await login(bob), C = await login(carol);await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token, tB = (await face(B, 'gitoriaMakeToken', ['b'])).token, tC = (await face(C, 'gitoriaMakeToken', ['c'])).token;const derivedRepo = await face(A, 'gitoriaCreateRepo', ['', 'derived', '', false, ' Hyper Conductor ++ ']);check('repo derives a lowercase address from Name and trims the stored title', derivedRepo?.repo?.slug === 'hyper-conductor' && derivedRepo.repo.title === 'Hyper Conductor ++');const explicitRepo = await face(A, 'gitoriaCreateRepo', ['chosen-address', '', '', false, 'Another Name']);check('repo explicit Address stays independent from Name', explicitRepo?.repo?.slug === 'chosen-address' && explicitRepo.repo.title === 'Another Name');const derivedOrg = await face(A, 'gitoriaCreateOrg', ['', false, 'EinicherAI']);check('organization derives address separately from Name', derivedOrg?.org?.slug === 'einicherai' && derivedOrg.org.title === 'EinicherAI');check('runs of punctuation become one hyphen without edge hyphens', (await face(A, 'gitoriaCreateOrg', ['', false, ' !!! Team ++ 9 ??? ']))?.org?.slug === 'team-9');check('derived repo/org addresses share the existing namespace', !!(await face(A, 'gitoriaCreateOrg', ['', false, 'Hyper Conductor']))?.error && !!(await face(A, 'gitoriaCreateRepo', ['', '', '', false, 'EinicherAI']))?.error);check('empty derivations and overlong names are refused', !!(await face(A, 'gitoriaCreateOrg', ['', false, '!!!']))?.error && !!(await face(A, 'gitoriaCreateRepo', ['', '', '', false, 'x'.repeat(81)]))?.error);const createApi = body => raw('POST', '/api/repos', { headers: { authorization: 'Bearer ' + tA, 'content-type': 'application/json' }, body: J(body) });const apiNamed = await createApi({ name: 'api-explicit', title: 'API display name' });const apiDerived = await createApi({ name: '', title: 'API Auto Address' });check('POST /api/repos accepts title and explicit or derived addresses additively', apiNamed.status === 201 && JSON.parse(apiNamed.body).title === 'API display name' && apiDerived.status === 201 && JSON.parse(apiDerived.body).slug === 'api-auto-address');check('POST /api/repos validates title type and length', (await createApi({ name: 'bad-title-type', title: 12 })).status === 422 && (await createApi({ name: 'bad-title-length', title: 'x'.repeat(81) })).status === 422);check('only organization owner can edit its Name', !!(await face(B, 'gitoriaSetOrgTitle', ['einicherai', 'Stolen']))?.error && !!(await face(null, 'gitoriaSetOrgTitle', ['einicherai', 'Stolen']))?.error);await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'EinicherAI renamed']);await face(A, 'gitoriaSetOrgPrivate', ['einicherai', true]);const privateOrgPage = await get('/', { host: `einicherai.${HOSTNAME}:${PORT}`, cookie: A.cookie });check('organization Name survives visibility changes and slug stays stable', privateOrgPage.body.includes('EinicherAI renamed') && privateOrgPage.body.includes('id="org-address-name"') && privateOrgPage.body.includes('einicherai'));await face(A, 'gitoriaSetOrgPrivate', ['einicherai', false]);check('organization Name validates plain text and length', !!(await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'x'.repeat(81)]))?.error && !!(await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'bad\nname']))?.error);check('organization Name can be cleared to its address', (await face(A, 'gitoriaSetOrgTitle', ['einicherai', '']))?.org?.heading === 'einicherai');await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'EinicherAI renamed']);const orgPage = await get('/', { host: `einicherai.${HOSTNAME}:${PORT}`, cookie: A.cookie });check('organization heading, address and window title show saved Name', orgPage.body.includes('EinicherAI renamed') && orgPage.body.includes('id="org-address-name"') && orgPage.body.includes('<title>EinicherAI renamed · gitoria</title>'));const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });const host = name => `${name}.${HOSTNAME}:${PORT}`;const at = (name, path = '/', cookie = A.cookie) => get(path, { host: host(name), cookie });const rename = (name, to, who = A, org = name.includes('/') ? name.split('/')[0] : '') => face(who, 'gitoriaRenameRepo', [name, to, org]);const title = (name, value, who = A) => face(who, 'gitoriaSetRepoTitle', [name, value]);const oldUrl = `http://a:${tA}@routger.${HOSTNAME}:${PORT}/routger.git`;g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# History retained\n'); g('add', '-A'); g('commit', '-q', '-m', 'first');const created = await face(A, 'gitoriaCreate', ['routger', 'rename gate']); const rid = created.repo.id;g('push', '-q', oldUrl, 'main'); const mainSha = g('rev-parse', 'HEAD').trim();g('checkout', '-q', '-b', 'feature'); g('commit', '-q', '--allow-empty', '-m', '|||PR retained pull'); const head = g('rev-parse', 'HEAD').trim(); g('push', '-q', oldUrl, 'feature');const added = await face(A, 'gitoriaChangeMember', ['routger', 'Bob', true]); const bobId = added.members[0].id;const appAdded = await face(A, 'gitoriaAppAdd', ['routger', 'Rename reviewer', `http://127.0.0.1:${RPORT}/a`]);const appId = appAdded.rows[0].id;const appToken = JSON.parse((await raw('POST', '/api/apps/token', { host: host('routger'), headers: { authorization: 'Bearer ' + appAdded.key } })).body).token;const putContext = async (sha, context) => raw('PUT', '/api/statuses/' + sha, { host: host('routger'), headers: { authorization: 'Bearer ' + appToken, 'content-type': 'application/json' }, body: J({ context, state: 'success' }) });await putContext(head, 'older-context'); await sleep(20);await putContext(mainSha, 'different-head-context');check('prefill reads newest app status across repo commits', (await face(A, 'gitoriaAppContext', ['routger', appId]))?.context === 'different-head-context');await sleep(20); await putContext(head, 'older-context');check('prefill follows updated existing status row', (await face(A, 'gitoriaAppContext', ['routger', appId]))?.context === 'older-context');const emptyApp = await face(A, 'gitoriaAppAdd', ['routger', 'No status yet', `http://127.0.0.1:${RPORT}/empty`]);const emptyAppId = emptyApp.rows.find(a => a.name === 'No status yet').id;check('app without statuses has empty context and non-owner cannot read suggestions', (await face(A, 'gitoriaAppContext', ['routger', emptyAppId]))?.context === '' && (await face(B, 'gitoriaAppContext', ['routger', appId])) == null);const api = (name, path) => raw('GET', path, { host: host(name), headers: { authorization: 'Bearer ' + appToken } });const pull = JSON.parse((await api('routger', '/api/pulls')).body).pulls[0];await face(A, 'gitoriaRequiredAdd', ['routger', appId, 'ci']);await face(A, 'gitoriaRequiredPersonAdd', ['routger', bobId]);const mixedRule = 'Merge is allowed when every app check above is success, or one of these people approved the current head.';const peopleRule = 'Merge needs an approval from one of these people.';const appsRule = 'Merge needs every app check above to be success.';const requirements = await face(A, 'gitoriaRequiredRead', ['routger']);check('Settings explains apps or people with clear form labels', (await at('routger', '/settings')).body.includes(mixedRule) && (await at('routger', '/settings')).body.includes('Require an app check') && (await at('routger', '/settings')).body.includes('Allow a person to approve'));await face(A, 'gitoriaRequiredRemove', ['routger', requirements.rows.find(r => !r.isPerson).id]);check('Settings explains people-only requirement', (await at('routger', '/settings')).body.includes(peopleRule));await face(A, 'gitoriaRequiredAdd', ['routger', appId, 'ci']);await face(A, 'gitoriaRequiredRemove', ['routger', requirements.rows.find(r => r.isPerson).id]);check('Settings explains apps-only requirement', (await at('routger', '/settings')).body.includes(appsRule));await face(A, 'gitoriaRequiredPersonAdd', ['routger', bobId]);await face(B, 'gitoriaPrApprove', ['routger', '' + pull.number, head, true]);check('owner, member, pull, approval and requirements fixture exists', !!rid && !!pull.number);await face(A, 'gitoriaCreate', ['taken', 'taken']); await face(A, 'gitoriaCreateOrg', ['occupied', false]);await face(A, 'gitoriaCreate', ['other', 'other']); await rename('other', 'other-new');for (const name of ['taken', 'occupied', 'other', 'INVALID', 'org/name']) check('rename refuses ' + name, !!(await rename('routger', name))?.error);check('non-owner and anonymous rename refused by server', !!(await rename('routger', 'stolen', B))?.error && !!(await rename('routger', 'stolen', null))?.error);check('non-owner display-name write refused by server', !!(await title('routger', 'stolen', B))?.error);check('too-long and multiline display names refused', !!(await title('routger', 'x'.repeat(81)))?.error && !!(await title('routger', 'bad\nname'))?.error);writeFileSync(join(GIT, 'routger.git/HEAD.lock'), 'busy');check('Git lock refuses rename without moving folder', !!(await rename('routger', 'hycon'))?.error && existsSync(join(GIT, 'routger.git')) && !existsSync(join(GIT, 'hycon.git')));rmSync(join(GIT, 'routger.git/HEAD.lock'));const pushProcess = spawn('git', ['receive-pack', join(GIT, 'routger.git')], { cwd: APP, stdio: ['pipe', 'pipe', 'pipe'] });await new Promise(resolve => pushProcess.stdout.once('data', resolve));try {check('active receive-pack does not block rename; its old path is preserved', (await rename('routger', 'inflight'))?.repo?.id === rid && lstatSync(join(GIT, 'routger.git')).isSymbolicLink());check('rename back while receive-pack holds its original path avoids a symlink loop', (await rename('inflight', 'routger'))?.repo?.id === rid && !lstatSync(join(GIT, 'routger.git')).isSymbolicLink() && realpathSync(join(GIT, 'inflight.git')) === realpathSync(join(GIT, 'routger.git')));}finally { pushProcess.stdin.end(); await new Promise(resolve => pushProcess.once('exit', resolve)); }const connect = await at('routger', '/settings/connect');const state = new URL(connect.headers.location).searchParams.get('state');await at('routger', '/settings/connected?code=rename&state=' + encodeURIComponent(state));check('display name saved', (await title('routger', 'Hyper Conductor'))?.repo?.title === 'Hyper Conductor');const moved = await rename('routger', 'hycon');check('owner live rename keeps repo id and title', moved?.repo?.slug === 'hycon' && moved.repo.id === rid && moved.repo.title === 'Hyper Conductor', J(moved));check('old name cannot be claimed by an organization', !!(await face(A, 'gitoriaCreateOrg', ['routger', false]))?.error);check('same folder history moved', lstatSync(join(GIT, 'routger.git')).isSymbolicLink() && !readlinkSync(join(GIT, 'routger.git')).startsWith('/') && execFileSync('git', ['--git-dir=' + join(GIT, 'hycon.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === mainSha);check('tickets connection stays attached', (await at('hycon', '/settings')).body.includes('W53 tickets'));await face(A, 'gitoriaAppPing', ['hycon', appId]);for (let i = 0; i < 100 && !got.some(x => { try { return JSON.parse(x.body).repo?.full === 'hycon'; } catch { return false; } }); i++) await sleep(100);check('new app event carries new full name and display title', got.some(x => { try { const r = JSON.parse(x.body).repo; return r?.id === rid && r.full === 'hycon' && r.title === 'Hyper Conductor'; } catch { return false; } }));check('new page has heading and window title', (await at('hycon')).status === 200 && /id="reponame"[^>]*>Hyper Conductor</.test((await at('hycon')).body) && /<title>Hyper Conductor · gitoria<\/title>/.test((await at('hycon')).body));const old = await at('routger');check('old page keeps GO34 moved view and link', old.status === 200 && old.body.includes('This repository moved to') && old.body.includes(`href="http://hycon.${HOSTNAME}:${PORT}/"`));const list = JSON.parse((await get('/api/repos')).body).repos;check('repo JSON and list add title without changing slug', list.some(r => r.id === rid && r.title === 'Hyper Conductor' && r.slug === 'hycon') && (await get('/')).body.includes('Hyper Conductor'));const retained = JSON.parse((await api('routger', '/api/pulls/' + pull.number)).body);check('old apps API base resolves to retained pull, approval and required rows', retained.number === pull.number && retained.head === head && retained.approvals.some(a => a.user.id === bobId) && retained.required[0]?.app?.id === appId && retained.approvers.some(a => a.user.id === bobId), J(retained).slice(0, 400));check('app exchanges key for token on old API base', (await raw('POST', '/api/apps/token', { host: host('routger'), headers: { authorization: 'Bearer ' + appAdded.key } })).status === 200);check('old HTTPS clone retains history', (() => { g('clone', '-q', oldUrl, join(STORE, 'clone')); return execFileSync('git', ['-C', join(STORE, 'clone'), 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() === mainSha; })());g('checkout', '-q', 'main'); g('commit', '-q', '--allow-empty', '-m', 'after rename'); g('push', '-q', oldUrl, 'main');execFileSync('git', ['-C', join(STORE, 'clone'), 'fetch', '-q'], { env: genv, stdio: ['ignore', 'pipe', 'pipe'] });check('old HTTPS push and fetch land at new name', execFileSync('git', ['--git-dir=' + join(GIT, 'hycon.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === g('rev-parse', 'HEAD').trim());const ssh = await get(`/__git/access?user=${bobId}&slug=routger&write=1`, { headers: { 'x-gitoria-secret': 'sshsecret-mm-gate' } });check('old SSH access resolves new folder and retains member', ssh.status === 200 && ssh.body.trim() === 'ok hycon');await rename('hycon', 'hycon-next');check('multiple moves retarget oldest forward in one hop', (await api('routger', '/api/pulls/' + pull.number)).status === 200 && (await get(`/__git/access?user=${bobId}&slug=routger&write=1`, { headers: { 'x-gitoria-secret': 'sshsecret-mm-gate' } })).body.trim() === 'ok hycon-next');check('rename back to own forward allowed', (await rename('hycon-next', 'routger'))?.repo?.id === rid);check('former current name now forwards after rename back', (await api('hycon-next', '/api/pulls/' + pull.number)).status === 200);await face(A, 'gitoriaCreateOrg', ['team', true]); await face(A, 'gitoriaCreateRepo', ['before', 'org repo', 'team', false]);check('org rename preserves org and effective visibility', (await rename('team/before', 'after'))?.repo?.slug === 'team/after' && (await at('team', '/after')).body.includes('Private'));check('org rename rejects reserved page name and transfers', !!(await rename('team/after', 'code'))?.error && !!(await rename('team/after', 'elsewhere/name'))?.error);const orgApp = await face(A, 'gitoriaAppAdd', ['team/after', 'Org reviewer', `http://127.0.0.1:${RPORT}/org`]);check('context suggestions reject an app from another repository', (await face(A, 'gitoriaAppContext', ['team/after', appId]))?.context === '');check('org old API bases resolve forward', (await raw('POST', '/api/before/apps/token', { host: host('team'), headers: { authorization: 'Bearer ' + orgApp.key } })).status === 200 && (await raw('POST', '/before/api/apps/token', { host: host('team'), headers: { authorization: 'Bearer ' + orgApp.key } })).status === 200);await title('team/after', 'Organization display name');check('organization list shows display name beside address', (await at('team')).body.includes('Organization display name') && (await at('team')).body.includes('team/after'));check('private org keeps old API private', (await get('/api/before/pulls/1', { host: host('team') })).status === 404);// W55: Settings → Rename also chooses the organization (none, or one the user belongs to).await face(A, 'gitoriaCreateOrg', ['mine', false]); await face(B, 'gitoriaCreateOrg', ['bobs', false]);await face(A, 'gitoriaCreate', ['mover', 'org mover']);const mvUrl = `http://a:${tA}@mover.${HOSTNAME}:${PORT}/mover.git`;g('checkout', '-q', 'main'); g('push', '-q', mvUrl, 'main');const settingsBody = (await at('mover', '/settings')).body;check('Settings shows an Organization select with None and an owned org, not the other user\'s', /<select[^>]*name="org"/.test(settingsBody) && settingsBody.includes('None (top level)') && settingsBody.includes('value="mine"') && !settingsBody.includes('value="bobs"') && settingsBody.includes('A repository that was private stays private'));check('into an organization the user does not belong to is refused', (await rename('mover', 'mover', A, 'bobs'))?.error === 'you can only move a repository into an organization you belong to');check('into an organization that does not exist is refused and none is created', (await rename('mover', 'mover', A, 'ghost-org'))?.error === 'you can only move a repository into an organization you belong to' && (await get('/api/repos', { cookie: A.cookie })).body.indexOf('ghost-org') < 0);check('non-owner cannot move into their own org either', !!(await rename('mover', 'mover', B, 'bobs'))?.error);check('a move that changes nothing is refused', !!(await rename('mover', 'mover', A, ''))?.error);const intoOrg = await rename('mover', 'mover', A, 'mine');check('top level repo moves into the user\'s own org', intoOrg?.repo?.slug === 'mine/mover' && intoOrg.repo.org === 'mine' && intoOrg.repo.id && intoOrg.repo.isPrivate === false, J(intoOrg));check('org page lists the moved repo', (await at('mine')).body.includes('mover'));const movedOld = await at('mover');check('old address shows moved to', movedOld.body.includes('This repository moved to') && movedOld.body.includes(`mine.${HOSTNAME}:${PORT}/mover`), movedOld.body.slice(0, 200));g('clone', '-q', mvUrl, join(STORE, 'mv-clone'));execFileSync('git', ['-C', join(STORE, 'mv-clone'), 'commit', '-q', '--allow-empty', '-m', 'via old url'], { env: genv });execFileSync('git', ['-C', join(STORE, 'mv-clone'), 'push', '-q', 'origin', 'main'], { env: genv });check('git clone and push over the old URL still work after moving into an org', execFileSync('git', ['--git-dir=' + join(GIT, 'mine/mover.git'), 'log', '-1', '--format=%s', 'main'], { encoding: 'utf8' }).trim() === 'via old url');await face(A, 'gitoriaSetOrgPrivate', ['mine', true]);const pm = await at('mine', '/mover', null); const pa = await at('mine', '/mover', A.cookie);check('a public repo in a private org is private by its organization', pm.status === 404 && pa.status === 200);const out = await rename('mine/mover', 'mover', A, '');check('moving out of a private org keeps the repository private (no leak)', out?.repo?.slug === 'mover' && out.repo.isPrivate === true && /No such repository/.test((await at('mover', '/', null)).body) && !/No such repository/.test((await at('mover', '/', A.cookie)).body), J(out));await face(A, 'gitoriaSetOrgPrivate', ['mine', false]);check('private repo moved between public orgs stays private', (await rename('mover', 'mover', A, 'mine'))?.repo?.isPrivate === true);await face(A, 'gitoriaCreate', ['pubone', 'public one']);check('a public repo moved out of a public org stays public', (await rename('pubone', 'pubone', A, 'mine'))?.repo?.isPrivate === false && (await rename('mine/pubone', 'pubone', A, ''))?.repo?.isPrivate === false);check('the repo id stays the same through every move', (await rename('mine/mover', 'mover', A, ''))?.repo?.id === intoOrg.repo.id);// Direct bare paths model the path captured by the SSH container before a rename.await face(A, 'gitoriaCreate', ['path-old', 'captured Git path']);g('push', '-q', join(GIT, 'path-old.git'), 'main');const pathClone = join(STORE, 'path-clone');g('clone', '-q', '--no-local', join(GIT, 'path-old.git'), pathClone);check('rename preserves a previously cloned direct Git origin', !!(await rename('path-old', 'path-new'))?.repo);const pathGit = (...args) => execFileSync('git', args, { cwd: pathClone, env: genv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });pathGit('commit', '-q', '--allow-empty', '-m', 'push after captured-path rename');pathGit('push', '-q', 'origin', 'main');const capturedSha = pathGit('rev-parse', 'HEAD').trim();check('clone made through old bare path pushes to the moved folder', execFileSync('git', ['--git-dir=' + join(GIT, 'path-new.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === capturedSha);await rename('path-new', 'path-third'); await rename('path-third', 'path-old');pathGit('commit', '-q', '--allow-empty', '-m', 'after rename-back'); pathGit('push', '-q', 'origin', 'main');check('all filesystem aliases resolve directly after later moves and rename-back', ['path-new', 'path-third'].every(name => realpathSync(join(GIT, name + '.git')) === realpathSync(join(GIT, 'path-old.git')) && readlinkSync(join(GIT, name + '.git')) === 'path-old.git'));await face(A, 'gitoriaCreateRepo', ['path-org', '', 'team', false]);g('push', '-q', join(GIT, 'team/path-org.git'), 'main');await rename('team/path-org', 'path-org-new');check('organization filesystem alias is relative to its containing directory', readlinkSync(join(GIT, 'team/path-org.git')) === '../team/path-org-new.git' && execFileSync('git', ['--git-dir=' + join(GIT, 'team/path-org.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === g('rev-parse', 'main').trim());await rename('team/path-org-new', 'path-org');check('organization rename-back replaces its own symlink with the bare directory', !lstatSync(join(GIT, 'team/path-org.git')).isSymbolicLink() && realpathSync(join(GIT, 'team/path-org-new.git')) === realpathSync(join(GIT, 'team/path-org.git')));// Real ticket notifications before and after rename, using only this gate's receiver.await face(A, 'gitoriaCreate', ['ticket-old', 'notification dedup']);const ticketConnect = await at('ticket-old', '/settings/connect');const ticketState = new URL(ticketConnect.headers.location).searchParams.get('state');await at('ticket-old', '/settings/connected?code=rename&state=' + encodeURIComponent(ticketState));const ticketUrl = name => `http://a:${tA}@${name}.${HOSTNAME}:${PORT}/${name}.git`;const ticketPush = (name, ref) => new Promise((resolve, reject) => {const p = spawn('git', ['push', '-q', ticketUrl(name), ref], { cwd: W, env: genv, stdio: ['ignore', 'pipe', 'pipe'] });let error = ''; p.stderr.on('data', d => error += d);p.on('error', reject); p.on('close', code => code === 0 ? resolve() : reject(new Error('ticket fixture push: ' + error)));});g('checkout', '-q', 'main'); g('commit', '-q', '--allow-empty', '-m', 'mention #11'); await ticketPush('ticket-old', 'main');g('checkout', '-q', '-b', 'ticket-fix'); g('commit', '-q', '--allow-empty', '-m', '|||PR fixes #12'); const ticketHead = g('rev-parse', 'HEAD').trim(); await ticketPush('ticket-old', 'ticket-fix');const ticketMerged = await face(A, 'gitoriaMergePull', ['ticket-old', ticketHead]);const notifications = () => got.filter(x => /^\/api\/projects\/w53\/tickets\/\d+\/(comments|state)$/.test(x.path));const oldNotifications = notifications();check('ticket fixture emitted real comments and a merged-PR review state', !ticketMerged?.error && oldNotifications.some(x => x.path.endsWith('/comments')) && oldNotifications.some(x => x.path.endsWith('/state')));await rename('ticket-old', 'ticket-new');g('checkout', '-q', 'main'); g('fetch', '-q', ticketUrl('ticket-new'), 'main'); g('merge', '-q', '--ff-only', 'FETCH_HEAD');g('commit', '-q', '--allow-empty', '-m', 'push without new references'); await ticketPush('ticket-new', 'main');check('rename then push repeats no old ticket comments or state changes', notifications().length === oldNotifications.length, J(notifications().map(x => x.path)));g('commit', '-q', '--allow-empty', '-m', 'new mention #13'); await ticketPush('ticket-old', 'main');check('new ticket references still notify once through old forwarded URL', notifications().length === oldNotifications.length + 1 && notifications().at(-1).path.endsWith('/13/comments'), J(notifications().map(x => x.path)));await rename('ticket-new', 'ticket-old');g('commit', '-q', '--allow-empty', '-m', 'push after ticket rename-back'); await ticketPush('ticket-old', 'main');check('ticket dedup history also survives rename-back', notifications().length === oldNotifications.length + 1);g('checkout', '-q', 'feature');if (process.env.HL_CDP_URL) {chromeLock = spawn('timeout', ['600', 'flock', '/media/STORAGE/claude-scratch/atlas/lisbeth.lock', 'sh', '-c', 'echo locked; cat'], { cwd: APP, stdio: ['pipe', 'pipe', 'inherit'] });await new Promise((resolve, reject) => { chromeLock.stdout.once('data', resolve); chromeLock.once('exit', () => reject(new Error('Chrome lock unavailable'))); });beforePages = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');writeFileSync(join(STORE, 'chrome-before.json'), J(beforePages.map(t => ({ id: t.id, title: t.title, url: t.url.split('?')[0] }))));}browser = await launchBrowser({ debugPortRange: CHROME });if (browser.proc) writeFileSync(join(STORE, 'browser-pid.txt'), String(browser.proc.pid));pg = await browser.newPage(); await pg.send('Network.enable');if (process.env.HL_CDP_URL) {const wait = pg.waitFor.bind(pg); pg.waitFor = (expression, options = {}) => wait(expression, { ...options, timeout: options.timeout || 30000 });}await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'routger.' + HOSTNAME, path: '/' });for (const [path, prefix] of [['/', ''], ['/code', 'Code · '], ['/branch/main', 'Branch · '], ['/commit/' + head, 'Commit · '], ['/pulls', 'Pull requests · '], ['/pulls/' + pull.number, 'Pull request #' + pull.number + ' · '], ['/releases', 'Releases · '], ['/tickets', 'Tickets · '], ['/settings', 'Settings · ']]) {await pg.goto(`http://routger.${HOSTNAME}:${PORT}` + path);await pg.waitFor('!!window.__hl && window.__hl.socket?.readyState === 1');await pg.evaluate('window.__w54KeptPage = 54');const newTitle = 'Kept page ' + path;await title('routger', newTitle);await pg.waitFor(`document.title === ${J(prefix)} + ${J(newTitle)} + ' · gitoria'`);check('kept ' + path + ' receives updated window title from another writer', await pg.evaluate('window.__w54KeptPage === 54'));await title('routger', 'Hyper Conductor');await pg.waitFor(`document.title === ${J(prefix)} + 'Hyper Conductor · gitoria'`);}const key = async name => { const n = { Tab: 9, Enter: 13, Home: 36, ArrowDown: 40 }[name]; await pg.send('Input.dispatchKeyEvent', { type: 'keyDown', key: name, code: name, windowsVirtualKeyCode: n, ...(name === 'Enter' ? { text: '\r' } : {}) }); await pg.send('Input.dispatchKeyEvent', { type: 'keyUp', key: name, code: name, windowsVirtualKeyCode: n }); };const tabTo = async selector => { for (let i = 0; i < 120; i++) { await key('Tab'); if (await pg.evaluate(`document.activeElement === document.querySelector(${J(selector)})`)) return; } throw new Error('Tab cannot reach ' + selector); };const chooseApp = async id => {await tabTo('#requiredapp');const index = await pg.evaluate(`Array.from(document.querySelector('#requiredapp').options).findIndex(o => o.value === ${J(id)})`);if (index < 0) throw new Error('missing app option');await key('Home'); for (let i = 0; i < index; i++) await key('ArrowDown');};const visit = async name => { await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: name + '.' + HOSTNAME, path: '/' }); await pg.goto(`http://${name}.${HOSTNAME}:${PORT}/settings`); await pg.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#rename-name')`, { timeout: 30000 }); };const formShot = async (selector, name) => {await pg.evaluate(`new Promise(resolve => { const r = document.querySelector(${J(selector)}).getBoundingClientRect(); window.scrollTo({ top: Math.max(0, r.top + scrollY - 64), behavior: 'instant' }); requestAnimationFrame(() => requestAnimationFrame(resolve)); })`);const box = await pg.evaluate(`(() => { const r = document.querySelector(${J(selector)}).getBoundingClientRect(); return { x: r.x + scrollX, y: r.y + scrollY, width: r.width, height: r.height, scale: 1 }; })()`);const shot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: box });writeFileSync(join(STORE, name), Buffer.from(shot.data, 'base64'));};let current = 'routger';for (const [width, height] of [[390, 844], [800, 1280], [1280, 800]]) {await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });await visit(current);await pg.send('Page.bringToFront');await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(mixedRule)}`);await chooseApp(appId);await pg.waitFor(`document.querySelector('#requiredcontext')?.value === 'older-context'`);await pg.type('#requiredcontext', 'editable-context', { clear: true });check(`${width}: selected app prefills its latest context and allows editing`, await pg.evaluate(`document.querySelector('#requiredcontext').value === 'editable-context'`));await chooseApp(emptyAppId);await pg.waitFor(`document.querySelector('#requiredcontext')?.value === ''`);await chooseApp(appId);await pg.waitFor(`document.querySelector('#requiredcontext')?.value === 'older-context'`);check(`${width}: changing apps clears absent history and restores newest context`, true);await formShot('#required', `merge-rule-${width}.png`);const liveRows = (await face(A, 'gitoriaRequiredRead', [current])).rows;await face(A, 'gitoriaRequiredRemove', [current, liveRows.find(r => !r.isPerson).id]);await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(peopleRule)}`);await face(A, 'gitoriaRequiredAdd', [current, appId, 'ci']);await face(A, 'gitoriaRequiredRemove', [current, liveRows.find(r => r.isPerson).id]);await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(appsRule)}`);await face(A, 'gitoriaRequiredPersonAdd', [current, bobId]);await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(mixedRule)}`);check(`${width}: merge-rule line follows live apps/people changes`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));const beforeShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `before-${width}x${height}.png`), Buffer.from(beforeShot.data, 'base64'));await tabTo('#display-name'); await pg.type('#display-name', 'Keyboard title ' + width, { clear: true }); await key('Enter');await pg.waitFor(`document.querySelector('#reponame').textContent === 'Keyboard title ${width}' && document.title.includes('Keyboard title ${width}')`);check(`${width}: title Enter submission updates heading and window title`, await pg.evaluate(`document.title.includes('Keyboard title ${width}')`));const titleShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `title-${width}x${height}.png`), Buffer.from(titleShot.data, 'base64'));await visit(current);check(`${width}: reload retains display name`, await pg.evaluate(`document.querySelector('#display-name').value === 'Keyboard title ${width}'`));await tabTo('#navcode'); await key('Enter'); await pg.waitFor(`location.pathname === '/code' && !!document.querySelector('#entries') && !document.querySelector('#display-name')`);const history = await pg.send('Page.getNavigationHistory'); await pg.send('Page.navigateToHistoryEntry', { entryId: history.entries[history.currentIndex - 1].id });await pg.waitFor(`!!document.querySelector('#display-name') && document.title.startsWith('Settings')`);check(`${width}: Back restores saved title and address`, await pg.evaluate(`document.querySelector('#display-name').value === 'Keyboard title ${width}' && location.pathname === '/settings'`));await tabTo('#display-name'); await pg.type('#display-name', '', { clear: true }); await tabTo('#save-title'); await key('Enter');await pg.waitFor(`document.querySelector('#reponame').textContent === ${J(current)} && document.title.includes(${J(current)})`);check(`${width}: keyboard clears title to address name`, await pg.evaluate(`!document.querySelector('#repo-address-name') && document.title.includes(${J(current)})`));await tabTo('#rename-name'); const next = 'keyboard-' + width; await pg.type('#rename-name', next, { clear: true });// The new subdomain has its own host-only test cookie.await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: next + '.' + HOSTNAME, path: '/' });await key('Enter'); await pg.waitFor(`location.hostname === '${next}.${HOSTNAME}' && !!document.querySelector('#rename-name')`, { timeout: 30000 });check(`${width}: Enter renames and browser lands at new Settings`, await pg.evaluate(`document.querySelector('#reponame').textContent === '${next}'`));current = next;check(`${width}: form fits viewport`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));const shot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `rename-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], url: `http://${HOSTNAME}:${PORT}/` });await pg.goto(`http://${HOSTNAME}:${PORT}/`); await pg.waitFor(`!!document.querySelector('#repo-name') && window.__hl?.socket?.readyState === 1`);const repoLabel = 'Repo keyboard ' + width, repoAddress = width === 800 ? 'explicit-repo-800' : 'repo-keyboard-' + width;await tabTo('#repo-name'); await pg.type('#repo-name', repoLabel, { clear: true });await tabTo('#slug'); await pg.type('#slug', width === 800 ? repoAddress : '', { clear: true });await formShot('#createform', `create-repo-${width}.png`);await tabTo('#createsave'); await key('Enter');await pg.waitFor(`document.querySelector('#created')?.textContent.includes(${J(repoAddress)})`);check(`${width}: repository Name and Address submit from keyboard`, await pg.evaluate(`document.querySelector('#repos').textContent.includes(${J(repoLabel)})`));const orgLabel = 'Org keyboard ' + width, orgAddress = width === 800 ? 'explicit-org-800' : 'org-keyboard-' + width;await tabTo('#org-name'); await pg.type('#org-name', orgLabel, { clear: true });await tabTo('#orgslug'); await pg.type('#orgslug', width === 800 ? orgAddress : '', { clear: true });await formShot('#orgform', `create-org-${width}.png`);await tabTo('#orgsave'); await key('Enter');await pg.waitFor(`document.querySelector('#created')?.textContent.includes(${J(orgAddress)})`);check(`${width}: organization Name and Address submit from keyboard`, await pg.evaluate(`document.querySelector('#orgs').textContent.includes(${J(orgLabel)})`));await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: orgAddress + '.' + HOSTNAME, path: '/' });await pg.goto(`http://${orgAddress}.${HOSTNAME}:${PORT}/`); await pg.waitFor(`!!document.querySelector('#organization-name') && window.__hl?.socket?.readyState === 1`);const orgNewName = 'Named organization ' + width;await tabTo('#organization-name'); await pg.type('#organization-name', orgNewName, { clear: true }); await key('Enter');await pg.waitFor(`document.querySelector('#orgname').textContent === ${J(orgNewName)} && document.title.includes(${J(orgNewName)})`);check(`${width}: owner changes org Name without changing Address`, await pg.evaluate(`location.hostname === ${J(orgAddress + '.' + HOSTNAME)} && document.querySelector('#org-address-name').textContent === ${J(orgAddress)}`));await pg.goto(`http://${orgAddress}.${HOSTNAME}:${PORT}/`); await pg.waitFor(`document.querySelector('#organization-name')?.value === ${J(orgNewName)}`);check(`${width}: org Name survives reload and fits viewport`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));const orgShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `org-name-${width}.png`), Buffer.from(orgShot.data, 'base64'));if (process.env.HL_CDP_URL) {await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'team.' + HOSTNAME, path: '/' });for (const [label, url] of [['main-list', `http://${HOSTNAME}:${PORT}/`], ['org-list', `http://team.${HOSTNAME}:${PORT}/`]]) {if (label === 'main-list') await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], url: `http://${HOSTNAME}:${PORT}/` });await pg.goto(url); await pg.waitFor(`document.querySelector('#repos')?.textContent.includes('Organization display name')`);check(`${width}: ${label} display name fits`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));const listShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `${label}-${width}x${height}.png`), Buffer.from(listShot.data, 'base64'));}}}// W55: choose the organization in Settings with the keyboard at phone and desktop width.for (const [width, height] of [[390, 844], [1280, 800]]) {await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });const nm = 'orgmove-' + width;await face(A, 'gitoriaCreate', [nm, 'browser org move']);await face(A, 'gitoriaSetOrgPrivate', ['mine', false]);await visit(nm);check(`${width}: Organization select starts on None and lists the owned org`, await pg.evaluate(`(() => { const s = document.querySelector('#rename-org'); return !!s && s.value === '' && [...s.options].map(o => o.value).includes('mine') && !s.closest('form').querySelectorAll('form').length; })()`));check(`${width}: the select sits in the one Rename form with the privacy line`, await pg.evaluate(`(() => { const f = document.querySelector('#rename-form'); return f.contains(document.querySelector('#rename-org')) && f.contains(document.querySelector('#rename-name')) && f.textContent.includes('A repository that was private stays private; change that below.') && document.documentElement.scrollWidth <= innerWidth; })()`));await formShot('#rename-form', `org-select-${width}.png`);await tabTo('#rename-org');const idx = await pg.evaluate(`[...document.querySelector('#rename-org').options].findIndex(o => o.value === 'mine')`);for (let i = 0; i < idx; i++) await key('ArrowDown');await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'mine.' + HOSTNAME, path: '/' });await tabTo('#rename-name'); await key('Enter');await pg.waitFor(`location.hostname === 'mine.${HOSTNAME}' && location.pathname === '/${nm}/settings' && !!document.querySelector('#rename-org')`, { timeout: 30000 });check(`${width}: Enter moves the repo into the org and the page lands at its new Settings`, await pg.evaluate(`document.querySelector('#rename-org').value === 'mine' && document.querySelector('#rename-name').value === ${J(nm)}`));await formShot('#rename-form', `org-moved-${width}.png`);const oldPage = await at(nm);check(`${width}: old address shows moved to`, oldPage.body.includes('This repository moved to'));await tabTo('#rename-org'); await key('Home'); await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: nm + '.' + HOSTNAME, path: '/' });await tabTo('#rename-name'); await key('Enter');await pg.waitFor(`location.hostname === '${nm}.${HOSTNAME}' && location.pathname === '/settings' && !!document.querySelector('#rename-org')`, { timeout: 30000 });check(`${width}: choosing None moves it back to the top level`, await pg.evaluate(`document.querySelector('#rename-org').value === ''`));}// W55 round 2: an OPEN list of the source organization drops the repo when it moves away (to the top level and to another org).await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });await face(A, 'gitoriaCreateOrg', ['mine2', false]);await face(A, 'gitoriaCreateRepo', ['leaver-a', '', 'mine', false]); await face(A, 'gitoriaCreateRepo', ['leaver-b', '', 'mine', false]);await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'mine.' + HOSTNAME, path: '/' });await pg.goto(`http://mine.${HOSTNAME}:${PORT}/`);await pg.waitFor(`window.__hl?.socket?.readyState === 1 && document.querySelector('#repos')?.textContent.includes('leaver-a') && document.querySelector('#repos').textContent.includes('leaver-b')`);await rename('mine/leaver-a', 'leaver-a', A, '');await pg.waitFor(`!document.querySelector('#repos').textContent.includes('leaver-a')`);check('open org list drops a repo moved to the top level and keeps the others', await pg.evaluate(`document.querySelector('#repos').textContent.includes('leaver-b')`));await rename('mine/leaver-b', 'leaver-b', A, 'mine2');await pg.waitFor(`!document.querySelector('#repos').textContent.includes('leaver-b')`);check('open org list drops a repo moved to another org', await pg.evaluate(`!document.querySelector('#repos').textContent.includes('leaver-b')`));await pg.goto(`http://mine.${HOSTNAME}:${PORT}/`); await pg.waitFor(`!!document.querySelector('#repos')`);check('after a reload the source org list still lacks both', await pg.evaluate(`!/leaver-/.test(document.querySelector('#repos').textContent)`));// W55 round 3: who hears "left the organization" is decided by the readers BEFORE the move.await face(A, 'gitoriaCreateOrg', ['pubo', false]); await face(A, 'gitoriaCreateOrg', ['privo', true]);const secretId = (await face(A, 'gitoriaCreateRepo', ['secret-out', '', 'pubo', true]))?.repo?.id; const openId = (await face(A, 'gitoriaCreateRepo', ['open-out', '', 'pubo', false]))?.repo?.id;await face(A, 'gitoriaCreateRepo', ['member-out', '', 'privo', false]); await face(A, 'gitoriaChangeMember', ['privo/member-out', 'Bob', true]);const frames = [];const stopFrames = browser.conn.onEvent(m => { if (m.method === 'Network.webSocketFrameReceived') { const d = m.params?.response?.payloadData || ''; frames.push({ sid: m.sessionId, text: d + '|' + Buffer.from(d, 'base64').toString('latin1') }); } });anon = await browser.newPage(); await anon.send('Network.enable');bobPage = await browser.newPage(); await bobPage.send('Network.enable');await bobPage.send('Network.setCookie', { name: 'gitoriasid', value: B.cookie.split('=')[1], domain: 'privo.' + HOSTNAME, path: '/' });await anon.goto(`http://pubo.${HOSTNAME}:${PORT}/`);await anon.waitFor(`window.__hl?.socket?.readyState === 1 && document.querySelector('#repos')?.textContent.includes('open-out')`);check('anonymous observer on a public org page never saw the private repo', await anon.evaluate(`!document.querySelector('#repos').textContent.includes('secret-out')`));await bobPage.goto(`http://privo.${HOSTNAME}:${PORT}/`);await bobPage.waitFor(`window.__hl?.socket?.readyState === 1 && document.querySelector('#repos')?.textContent.includes('member-out')`);check('fixture ids found', !!secretId && !!openId);await rename('pubo/open-out', 'open-out', A, '');await anon.waitFor(`!document.querySelector('#repos').textContent.includes('open-out')`);check('control: the anonymous observer hears a PUBLIC repo leave (its frames carry the id)', frames.some(f => f.sid === anon.sessionId && f.text.includes(openId)));await rename('pubo/secret-out', 'secret-out', A, '');await sleep(1500);check('anonymous observer does not receive the event when a PRIVATE repo leaves the public org', !frames.some(f => f.sid === anon.sessionId && f.text.includes(secretId)) && !frames.some(f => f.sid === anon.sessionId && f.text.includes('secret-out')));// replay: each move keeps its own readers. Private repo leaves (anon must not hear), is made public, goes in again and leaves again (anon hears that one only).const replayId = (await face(A, 'gitoriaCreateRepo', ['replay-x', '', 'pubo', true]))?.repo?.id;await rename('pubo/replay-x', 'replay-x', A, ''); await face(A, 'gitoriaSetPrivate', ['replay-x', false]);await rename('replay-x', 'replay-x', A, 'pubo'); await rename('pubo/replay-x', 'replay-x', A, '');await anon.waitFor(`!document.querySelector('#repos').textContent.includes('replay-x')`);await anon.evaluate(`window.__hl.socket.close()`); await sleep(500);await anon.waitFor(`window.__hl?.socket?.readyState === 1`, { timeout: 30000 }); await sleep(1500);const replayFrames = frames.filter(f => f.sid === anon.sessionId && f.text.includes(replayId) && f.text.includes('repoLeftOrg')).length;check('anonymous tab: across private-leave, make-public, re-enter, leave and a reconnect it gets exactly one leave event (the last, public one)', replayFrames === 1, 'frames with the id: ' + replayFrames);await rename('privo/member-out', 'member-out', A, '');await bobPage.waitFor(`!document.querySelector('#repos').textContent.includes('member-out')`);check('a member of only that one repo has the row dropped from the open private-org list', true);stopFrames(); await anon.close(); await bobPage.close();} catch (e) {check('the gate ran without an exception', false, String(e && e.stack || e).replace(/(?:gtr|gat|gak)_[a-f0-9]+/g, '[redacted]'));if (log) console.log(log.slice(-3000));if (pg) { console.log(pg.dumpConsole()); console.log(await pg.evaluate(`JSON.stringify({ title: document.title, heading: document.querySelector('#reponame')?.textContent, input: document.querySelector('#display-name')?.value, active: document.activeElement?.id, text: document.querySelector('#title-form')?.textContent })`)); }} finally {for (const t of [anon, bobPage]) { try { if (t) await t.close(); } catch {} }try { if (pg) await pg.close(); if (browser) { if (browser.owned) await browser.close(); else browser.conn.close(); } } catch {}if (beforePages) {let after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');if (pg && after.some(t => t.id === pg.targetId) && !beforePages.some(t => t.id === pg.targetId)) await fetch(process.env.HL_CDP_URL + '/json/close/' + pg.targetId);after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');writeFileSync(join(STORE, 'chrome-after.json'), J(after.map(t => ({ id: t.id, title: t.title, url: t.url.split('?')[0] }))));check('shared Chrome original tabs preserved and own tab closed', after.length === beforePages.length && after.every(t => beforePages.some(b => b.id === t.id)));}if (chromeLock) { chromeLock.stdin.end(); await new Promise(r => chromeLock.once('exit', r)); }await stop().catch(() => {}); try { receiver.close(); } catch {} try { ident && await ident.stop(); } catch {}writeFileSync(join(STORE, 'server.log'), log);console.log(`\n${passes} passed, ${failures} failed`); process.exit(failures ? 1 : 0);}
Branches
Latest commits
- fe209ffeMerge branch 'w56-owner-members' into mainGitoria
- fa0754c8|||PR repository owner transfer and members API (#55)mre
- 8862e537Merge branch 'w55-rename-org' into mainGitoria
- 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
- 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
- 499f25f2Review fixes for the Settings organization move (#53)mre
- ed3b922b|||PR move a repository into an organization in Settings (#53)mre
- 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
- 9f7ce8d8Preserve rename compatibility and live page titlesmre
- c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
- ce08920dMerge branch 'w52c-header-phone' into mainGitoria
- 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
- e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
- c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
- 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
- 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
- 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
- 155861f6Merge branch 'w52-person-approval' into mainGitoria
- b5435de8|||PR person approvals: second Kunibert round (#52)mre
- 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre