Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(ui): rp-032 rp-002 rp-005 close the review findings on the drag lanes
M9b9f0e913892
diff --git a/control-ui/components/GfsGrantPanel.tsx b/control-ui/components/GfsGrantPanel.tsxindex f84019c40..39163da7a 100644--- a/control-ui/components/GfsGrantPanel.tsx+++ b/control-ui/components/GfsGrantPanel.tsx@@ -153,6 +153,26 @@ function revokedSharesCopy(folderNames: string[]): string {return `The sharing entries on ${joinFolderNames(folderNames)} were revoked.`}+/**+ * The item's OWN surviving Editor access.+ *+ * A share-only direct row has no grant to rewrite, and a role change never+ * converts one into a grant (R1-M5) — so an Editor sharing entry on the item+ * itself SURVIVES the downgrade and the member keeps Editor access through+ * it. The operator must be told: in the confirmation BEFORE the write (the+ * consent) and in the outcome after it (the feedback).+ *+ * A direct GRANT is different: the change rewrites it, and RP-032 revokes the+ * conflicting sharing entries together with it, so nothing of it survives.+ */+function collectResidualDirectShareNames(+ direct: GfsExistingAccessItem | null,+ itemName: string+): string[] {+ if (!direct || direct.grantId !== null) return []+ return direct.shareEntries.some(entry => isEditorPermissions(entry.permissions)) ? [itemName] : []+}+/*** A role promise is only as good as the coverage it was made under: when the* inherited walk did not complete, an ancestor the operator cannot see may@@ -809,9 +829,16 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme// The surviving Editor shares are disclosed IN the confirmation, before// the operator approves a role that will not remove them. The folders// this change rewrites lose their conflicting sharing entries- // (RP-032), so only the share-only ancestors remain.+ // (RP-032), so what remains is the share-only ancestors this panel+ // cannot rewrite — plus a share-only Editor entry on the item ITSELF,+ // which no rewrite touches and therefore survives.residualEditorFolderNames:- nextRole === 'read' ? collectResidualEditorFolderNames(plan.shareOnlySources) : [],+ nextRole === 'read'+ ? [+ ...collectResidualEditorFolderNames(plan.shareOnlySources),+ ...collectResidualDirectShareNames(row.direct, resource.name),+ ]+ : [],})}@@ -975,9 +1002,15 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme}// Residual honesty (RP-032): the conflicting sharing entries are revoked// with the change, so what can still grant Editor is the share-only- // ancestor this panel cannot rewrite.+ // ancestor this panel cannot rewrite — and a share-only Editor entry on+ // the item itself, which this change never touches.const residualNames =- request.nextRole === 'read' ? collectResidualEditorFolderNames(request.residualSources) : []+ request.nextRole === 'read'+ ? [+ ...collectResidualEditorFolderNames(request.residualSources),+ ...collectResidualDirectShareNames(row.direct, resource.name),+ ]+ : []const details: string[] = []if (request.skippedFolderNames.length > 0) {details.push(diff --git a/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx b/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsxindex b2724e213..676abbeff 100644--- a/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx+++ b/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx@@ -939,6 +939,85 @@ describe('GfsGrantPanel inherited access', () => {expect(mockDeleteGfsShare).not.toHaveBeenCalled()})+ // RP-032 — the INVERSE combination: an inherited Editor grant plus a+ // DIRECT Editor share on the opened item, with no direct grant. The+ // downgrade rewrites the ancestor grant and (by the accepted semantics)+ // preserves the direct share-only access — so the member keeps Editor+ // access through it. The operator must be told BEFORE approving, and the+ // outcome must repeat it.+ it('discloses the surviving direct Editor share before and after the downgrade', async () => {+ const DIRECT_SHARE_ID = '18181818-1818-4181-8181-181818181818'+ mockGetGfsGrants.mockImplementation(async resourceId => {+ if (resourceId === FOLDER_ID) {+ return {+ items: [+ {+ id: FOLDER_GRANT_ID,+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ inherit: true,+ },+ ],+ }+ }+ // No direct grant on the opened item: its access is the share below.+ return { items: [] }+ })+ mockGetGfsShares.mockImplementation(async resourceId => ({+ items:+ resourceId === FILE_ID+ ? [+ {+ id: DIRECT_SHARE_ID,+ drive: 'main',+ resourceId: FILE_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ includeDescendants: true,+ },+ ]+ : [],+ }))+ renderPanel()++ const existing = await screen.findByRole('region', { name: 'People with access' })+ const miguelRow = await within(existing).findByTestId(miguelRowTestId)+ await chooseRole(miguelRow, 'Read')++ // CONSENT: the confirmation names the access that survives the change.+ const dialog = await screen.findByRole('alertdialog')+ expect(+ within(dialog).getByText(+ 'Sharing entries on report.md still grant Editor access. This change does not remove them.'+ )+ ).toBeTruthy()+ expect(mockPutGfsGrant).not.toHaveBeenCalled()++ fireEvent.click(within(dialog).getByRole('button', { name: 'Update role' }))++ // The ancestor grant is rewritten…+ await waitFor(() =>+ expect(mockPutGfsGrant).toHaveBeenCalledWith({+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'share'],+ inherit: true,+ })+ )+ // …the share-only direct row is neither converted nor revoked…+ expect(mockPutGfsGrant).toHaveBeenCalledTimes(1)+ expect(mockDeleteGfsShare).not.toHaveBeenCalledWith(DIRECT_SHARE_ID)+ // …and the outcome repeats the residual Editor access.+ expect(+ await screen.findByText(+ 'Changed grant access to Read-only on team-docs. Sharing entries on report.md still grant Editor access.'+ )+ ).toBeTruthy()+ })+// RP-032 — a revocation that fails is a PARTIAL outcome: the role changed,// but the link may still grant Editor, and the copy must say so.it('states the true partial outcome when a sharing entry cannot be revoked', async () => {diff --git a/control-ui/e2e/gfs-drag-and-drop.spec.ts b/control-ui/e2e/gfs-drag-and-drop.spec.tsindex 054d3cb15..80c1124d1 100644--- a/control-ui/e2e/gfs-drag-and-drop.spec.ts+++ b/control-ui/e2e/gfs-drag-and-drop.spec.ts@@ -195,6 +195,32 @@ async function cleanupGfsDragDropFixtures(page: Page, names: ReadonlySet<string>}}+/** The drive root's resource id, read through the operator plane. */+async function driveRootId(page: Page): Promise<string> {+ const response = await adminFetch(page, 'GET', '/control-api/api/v1/gfs/tree?drive=main')+ if (response.status !== 200) throw new Error(`drive tree failed with HTTP ${response.status}`)+ const rootResourceId = (response.data as { rootResourceId?: string }).rootResourceId+ if (!rootResourceId) throw new Error('the drive root id did not resolve')+ return rootResourceId+}++/** The resource id of a folder with an exact name, or null when it is absent. */+async function findChildByName(+ page: Page,+ parentResourceId: string,+ name: string+): Promise<string | null> {+ for (const child of await listChildren(page, parentResourceId)) {+ if (child.name === name) return child.resourceId+ }+ return null+}++/** The names of a folder's live children, read through the operator plane. */+async function childNames(page: Page, parentResourceId: string): Promise<string[]> {+ return (await listChildren(page, parentResourceId)).map(child => child.name)+}+async function beginJourney(page: Page): Promise<void> {assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)@@ -307,6 +333,19 @@ test.describe('EvenDrive drag and drop', () => {// (toasts auto-dismiss after 3.5s) and then the refreshed listing.await expect(toast(page, `Moved "${fileName}" to "${folderName}".`)).toBeVisible()await expect(resourceRow(page, fileName)).toHaveCount(0)+ // The business signal, not just the receipt: the file really is a+ // child of the destination folder now.+ const rootId = await driveRootId(page)+ const parentId = await findChildByName(page, rootId, parentName)+ expect(parentId).not.toBeNull()+ const destinationId = await findChildByName(page, parentId as string, folderName)+ expect(destinationId).not.toBeNull()+ await expect+ .poll(async () => (await childNames(page, destinationId as string)).includes(fileName), {+ timeout: 30_000,+ intervals: [250, 1_000],+ })+ .toBe(true)await screenshotAndLog(page, testInfo, 'gfs-dnd-file-move')} finally {await tempFile?.cleanup().catch(() => {})@@ -392,6 +431,19 @@ test.describe('EvenDrive drag and drop', () => {await expect(toast(page, 'access now follows the new location')).toBeVisible()await expect(dialog).toBeHidden({ timeout: 20_000 })await expect(resourceRow(page, sourceName)).toHaveCount(0)+ // The business signal: the moved folder really is a child of the+ // destination folder now.+ const rootId = await driveRootId(page)+ const parentId = await findChildByName(page, rootId, parentName)+ expect(parentId).not.toBeNull()+ const destinationId = await findChildByName(page, parentId as string, destinationName)+ expect(destinationId).not.toBeNull()+ await expect+ .poll(async () => (await childNames(page, destinationId as string)).includes(sourceName), {+ timeout: 30_000,+ intervals: [250, 1_000],+ })+ .toBe(true)await screenshotAndLog(page, testInfo, 'gfs-dnd-folder-commit')} finally {await cleanupGfsDragDropFixtures(page, new Set([parentName, sourceName, destinationName]))@@ -588,11 +640,8 @@ test.describe('EvenDrive drag and drop', () => {await expect(dialog).toBeVisible({ timeout: 20_000 })// Leave "Use a numbered name if needed" unchecked.await dialog.getByRole('button', { name: 'Move', exact: true }).click()- await page.waitForTimeout(1500)- const toastTexts = await page.locator('.cu-toast').allTextContents()- // eslint-disable-next-line no-console- console.log('POST-MOVE-TOASTS:', JSON.stringify(toastTexts))-+ // The refusal is a visible outcome, so the expectation below waits for+ // it — no fixed sleep and no toast dump.await expect(toast(page,diff --git a/control-ui/e2e/run-gfs-drag-and-drop.mjs b/control-ui/e2e/run-gfs-drag-and-drop.mjsindex f17125c37..00b370f57 100644--- a/control-ui/e2e/run-gfs-drag-and-drop.mjs+++ b/control-ui/e2e/run-gfs-drag-and-drop.mjs@@ -14,20 +14,29 @@// with an actionable message. It never silently degrades to "skip".// 2. The gate NEVER reports success for zero executed journeys, and never// reports success while any journey was skipped.-// 3. The live-fixture opt-in stays EXPLICIT. This gate is a separate,+// 3. The gate NEVER reports success for an INCOMPLETE report: every counter+// must be present, the report's journey inventory must reconcile with+// those counters, and the inventory must be exactly the set of journeys+// Playwright selected.+// 4. The live-fixture opt-in stays EXPLICIT. This gate is a separate,// named command; the ordinary unit/CI lanes never mutate the dev// environment, because nothing in `npm test` calls this file.//// Usage (from control-ui/):// QA_RECORDER_CONFIRM_MUTATIONS=1 \-// E2E_ADMIN_USER=<admin> ADMIN_PASSWORD=<password> \+// E2E_ADMIN_USER=<admin> E2E_ADMIN_PASSWORD=<password> \// CONTROL_UI_URL=http://127.0.0.1:<port> \// CONTROL_API_URL=http://127.0.0.1:<port> \// npm run e2e:gfs-drag-and-drop//// Exit codes: 0 = every requested journey ran and passed. 1 = the gate// refused to run, or the journey result was not a clean pass.-import { spawnSync } from 'node:child_process'+//+// NOTE: the Desktop lane owns a copy of this gate+// (desktop-app/test/e2e-playwright/run-gfs-drag-and-drop.mjs). The two+// copies must stay in sync: the reviewer's "both evaluators" finding was+// exactly a defect that lived in both.+import { execFileSync, spawnSync } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'@@ -47,6 +56,13 @@ export const ADMIN_PASSWORD_KEYS = [const PROBE_TIMEOUT_MS = 10_000const HEALTH_PATH = '/health'+const PLAYWRIGHT_ARGS = [+ 'test',+ '--config=playwright.config.ts',+ '--project=chromium',+ 'e2e/gfs-drag-and-drop.spec.ts',+ '--workers=1',+]/** First non-empty value among the candidate env names (never logged). */export function firstConfiguredValue(env, keys) {@@ -112,12 +128,82 @@ export function collectGateProblems(env) {return problems}+/**+ * The counters a Playwright JSON report must carry. A report without them is+ * INCOMPLETE: a missing counter is not "zero journeys", it is unknown, and+ * an unknown count can never certify a run.+ */+export const REQUIRED_REPORT_COUNTERS = ['expected', 'skipped', 'unexpected', 'flaky']++/**+ * Every journey a Playwright JSON report lists, with the outcome Playwright+ * recorded for it.+ *+ * The inventory is what makes a report verifiable: the counters are only a+ * summary of it, and a summary that does not match the detail it summarises+ * is not evidence. A journey with no recorded outcome is an incomplete+ * report.+ */+export function collectReportJourneys(report) {+ const journeys = []+ const walk = (suite, path) => {+ const title = typeof suite?.title === 'string' ? suite.title : ''+ const file = typeof suite?.file === 'string' ? suite.file : ''+ // The file-level suite repeats the file name; it is not part of a test's+ // title path.+ const nextPath = title && title !== file ? [...path, title] : path+ for (const spec of suite?.specs ?? []) {+ for (const test of spec?.tests ?? []) {+ const specTitle = String(spec?.title ?? '')+ journeys.push({+ identity: `${String(spec?.file ?? '')}::${[...nextPath, specTitle].join(' › ')}`,+ title: specTitle,+ file: String(spec?.file ?? ''),+ outcome: typeof test?.status === 'string' ? test.status : null,+ results: Array.isArray(test?.results) ? test.results.length : 0,+ })+ }+ }+ for (const child of suite?.suites ?? []) walk(child, nextPath)+ }+ for (const suite of report?.suites ?? []) walk(suite, [])+ return journeys+}++/**+ * The outcome tally of a report's inventory, computed the way Playwright+ * computes it (a journey with no result counts as skipped). A journey with an+ * outcome Playwright does not report is INCOMPLETE.+ */+export function tallyReportJourneys(journeys) {+ const tally = { expected: 0, skipped: 0, unexpected: 0, flaky: 0, incomplete: 0 }+ for (const journey of journeys) {+ const outcome = journey.results === 0 ? 'skipped' : journey.outcome+ if (+ outcome === 'expected' ||+ outcome === 'skipped' ||+ outcome === 'unexpected' ||+ outcome === 'flaky'+ ) {+ tally[outcome] += 1+ continue+ }+ tally.incomplete += 1+ }+ return tally+}+/*** The verdict of a Playwright JSON report. A run is a clean pass only when- * at least one journey actually executed, nothing was skipped, and nothing- * failed. A report that ran zero journeys is NOT a pass.+ * the report is COMPLETE, at least one journey actually executed, nothing+ * was skipped, and nothing failed.+ *+ * `selectedJourneys` is the inventory Playwright selected before the run (the+ * `--list` pass). When it is supplied, the report must describe exactly that+ * set: a report that lists fewer journeys than were selected is not evidence+ * for the run.*/-export function evaluateGateReport(report, run = { status: 0 }) {+export function evaluateGateReport(report, run = { status: 0 }, selectedJourneys = null) {const problems = []if (run.error || run.signal || run.status !== 0) {problems.push('Playwright did not exit successfully. The report cannot certify this run.')@@ -126,12 +212,64 @@ export function evaluateGateReport(report, run = { status: 0 }) {problems.push('Playwright reported a run-level error. The report cannot certify this run.')}const stats = report && typeof report === 'object' ? (report.stats ?? {}) : {}- const expected = Number(stats.expected ?? 0)- const skipped = Number(stats.skipped ?? 0)- const unexpected = Number(stats.unexpected ?? 0)- const flaky = Number(stats.flaky ?? 0)+ const counters = {}+ for (const key of REQUIRED_REPORT_COUNTERS) {+ const value = stats[key]+ if (!Number.isInteger(value) || value < 0) {+ problems.push(+ `The journey report has invalid result counts: "${key}" is missing or not a non-negative integer. ` ++ 'An incomplete report cannot certify this run.'+ )+ counters[key] = null+ continue+ }+ counters[key] = value+ }+ const expected = counters.expected ?? 0+ const skipped = counters.skipped ?? 0+ const unexpected = counters.unexpected ?? 0+ const flaky = counters.flaky ?? 0++ const journeys = collectReportJourneys(report)+ const tally = tallyReportJourneys(journeys)+ if (journeys.length === 0) {+ problems.push(+ 'The journey report lists no journeys. A report without its inventory cannot certify this run.'+ )+ }+ if (tally.incomplete > 0) {+ problems.push(+ `${tally.incomplete} journey(s) in the report carry no outcome. The report is incomplete.`+ )+ }+ const mismatched = REQUIRED_REPORT_COUNTERS.filter(+ key => counters[key] !== null && counters[key] !== tally[key]+ )+ if (mismatched.length > 0) {+ problems.push(+ `The journey report does not reconcile with its own inventory: ${mismatched.join(', ')} ` ++ `(report ${expected}/${skipped}/${unexpected}/${flaky}, ` ++ `inventory ${tally.expected}/${tally.skipped}/${tally.unexpected}/${tally.flaky}).`+ )+ }+ if (selectedJourneys) {+ const selected = new Set(selectedJourneys.map(journey => journey.identity))+ const reported = new Set(journeys.map(journey => journey.identity))+ const missing = [...selected].filter(identity => !reported.has(identity))+ const extra = [...reported].filter(identity => !selected.has(identity))+ if (missing.length > 0) {+ problems.push(+ `The journey report is missing ${missing.length} selected journey(s): ${missing.join(', ')}`+ )+ }+ if (extra.length > 0) {+ problems.push(+ `The journey report contains ${extra.length} journey(s) that were not selected: ${extra.join(', ')}`+ )+ }+ }- if (!Number.isFinite(expected) || expected <= 0) {+ if (expected <= 0) {problems.push('The journey suite executed zero journeys. A skipped suite is not a green result: ' +'check the mutation opt-in, the admin credential and the endpoint configuration.'@@ -140,17 +278,6 @@ export function evaluateGateReport(report, run = { status: 0 }) {if (skipped > 0) {problems.push(`${skipped} journey(s) were skipped. A skipped journey is not a green result.`)}- if (- !Number.isInteger(skipped) ||- skipped < 0 ||- !Number.isInteger(unexpected) ||- unexpected < 0 ||- !Number.isInteger(flaky) ||- flaky < 0 ||- !Number.isInteger(expected)- ) {- problems.push('The journey report has invalid result counts.')- }if (unexpected > 0) {problems.push(`${unexpected} journey(s) failed.`)}@@ -161,6 +288,52 @@ export function evaluateGateReport(report, run = { status: 0 }) {return { problems, stats: { expected, skipped, unexpected, flaky } }}+/**+ * The SANITIZED evidence file for this run: the tested revision, the+ * selected journeys, their outcomes and the process exit.+ *+ * The raw Playwright report carries error text, stdout and attachments, so+ * it stays private under the ignored artifact directory. This file is the+ * part a reviewer can read: no credentials, no cookies, no auth headers, no+ * request or response bodies — only what certifies WHICH journeys ran, on+ * WHICH revision, with WHICH exit code.+ */+export function writeSanitizedRunSummary({+ lane,+ revision,+ branch,+ command,+ report,+ run,+ selectedJourneys,+ verdict,+ filePath,+}) {+ const journeys = collectReportJourneys(report).map(journey => ({+ title: journey.title,+ status: journey.outcome ?? 'incomplete',+ }))+ const summary = {+ lane,+ revision,+ branch,+ command,+ processExit: typeof run?.status === 'number' ? run.status : null,+ signal: run?.signal ?? null,+ verdict,+ counts: {+ expected: Number(report?.stats?.expected ?? 0),+ skipped: Number(report?.stats?.skipped ?? 0),+ unexpected: Number(report?.stats?.unexpected ?? 0),+ flaky: Number(report?.stats?.flaky ?? 0),+ },+ selected: (selectedJourneys ?? []).map(journey => journey.title),+ journeys,+ }+ fs.writeFileSync(filePath, `${JSON.stringify(summary, null, 2)}\n`)+ return summary+}+/** Bounded reachability probe. Never prints the response body. */export async function probeReachable(url, timeoutMs = PROBE_TIMEOUT_MS) {try {@@ -175,6 +348,26 @@ export async function probeReachable(url, timeoutMs = PROBE_TIMEOUT_MS) {}}+/** The revision the lane ran against (never a branch guess). */+export function readTestedRevision(repoRoot) {+ try {+ return execFileSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()+ } catch {+ return 'unknown'+ }+}++/** The branch the lane ran on. */+export function readTestedBranch(repoRoot) {+ try {+ return execFileSync('git', ['-C', repoRoot, 'rev-parse', '--abbrev-ref', 'HEAD'], {+ encoding: 'utf8',+ }).trim()+ } catch {+ return 'unknown'+ }+}+function resolvePlaywrightBin() {const bin = path.join(APP_ROOT,@@ -196,6 +389,10 @@ function artifactDir() {return dir}+function readJson(filePath) {+ return JSON.parse(fs.readFileSync(filePath, 'utf8'))+}+async function main() {const env = process.envconst problems = collectGateProblems(env)@@ -225,30 +422,59 @@ async function main() {const dir = artifactDir()const reportPath = path.join(dir, 'playwright-report.json')+ const selectionPath = path.join(dir, 'playwright-selection.json')const playwrightBin = resolvePlaywrightBin()// A previous successful run must never supply evidence for a failed launch.fs.rmSync(reportPath, { force: true })+ fs.rmSync(selectionPath, { force: true })+ // Enumerate the journeys Playwright SELECTS before running them. The run's+ // report is reconciled against this inventory, so a report that describes+ // fewer journeys than were selected cannot certify the run.+ process.stdout.write('[E2E-GATE] enumerating the selected journeys\n')+ const selection = spawnSync(playwrightBin, [...PLAYWRIGHT_ARGS, '--list', '--reporter=json'], {+ cwd: APP_ROOT,+ stdio: 'inherit',+ timeout: 10 * 60_000,+ env: { ...env, PLAYWRIGHT_JSON_OUTPUT_NAME: selectionPath },+ })+ if (selection.status !== 0 || !fs.existsSync(selectionPath)) {+ process.stderr.write(+ '[E2E-GATE] Playwright could not enumerate the selected journeys. ' ++ 'The gate cannot certify this run.\n'+ )+ return 1+ }+ let selectedJourneys+ try {+ selectedJourneys = collectReportJourneys(readJson(selectionPath))+ } catch (error) {+ process.stderr.write(+ `[E2E-GATE] The Playwright selection report is unreadable: ${error instanceof Error ? error.message : String(error)}\n`+ )+ return 1+ }+ if (selectedJourneys.length === 0) {+ process.stderr.write(+ '[E2E-GATE] Playwright selected no journeys. The gate cannot certify this run.\n'+ )+ return 1+ }process.stdout.write(- `[E2E-GATE] running the EvenDrive drag-and-drop journeys (report: ${reportPath})\n`+ `[E2E-GATE] ${selectedJourneys.length} journey(s) selected: ${selectedJourneys+ .map(journey => journey.title)+ .join(' | ')}\n`)- const run = spawnSync(- playwrightBin,- [- 'test',- '--config=playwright.config.ts',- '--project=chromium',- 'e2e/gfs-drag-and-drop.spec.ts',- '--workers=1',- '--reporter=list,json',- ],- {- cwd: APP_ROOT,- stdio: 'inherit',- timeout: 75 * 60_000,- env: { ...env, PLAYWRIGHT_JSON_OUTPUT_NAME: reportPath },- }++ process.stdout.write(+ `[E2E-GATE] running the EvenDrive drag-and-drop journeys (report: ${reportPath})\n`)+ const run = spawnSync(playwrightBin, [...PLAYWRIGHT_ARGS, '--reporter=list,json'], {+ cwd: APP_ROOT,+ stdio: 'inherit',+ timeout: 75 * 60_000,+ env: { ...env, PLAYWRIGHT_JSON_OUTPUT_NAME: reportPath },+ })if (!fs.existsSync(reportPath)) {process.stderr.write(@@ -259,7 +485,7 @@ async function main() {let reporttry {- report = JSON.parse(fs.readFileSync(reportPath, 'utf8'))+ report = readJson(reportPath)} catch (error) {process.stderr.write(`[E2E-GATE] The Playwright JSON report is unreadable: ${error instanceof Error ? error.message : String(error)}\n`@@ -267,7 +493,20 @@ async function main() {return 1}- const verdict = evaluateGateReport(report, run)+ const verdict = evaluateGateReport(report, run, selectedJourneys)+ const summaryPath = path.join(dir, 'playwright-summary.json')+ writeSanitizedRunSummary({+ lane: 'control-ui',+ revision: readTestedRevision(REPO_ROOT),+ branch: readTestedBranch(REPO_ROOT),+ command: 'npm run e2e:gfs-drag-and-drop',+ report,+ run,+ selectedJourneys,+ verdict: verdict.problems.length > 0 ? 'fail' : 'pass',+ filePath: summaryPath,+ })+ process.stdout.write(`[E2E-GATE] sanitized summary: ${summaryPath}\n`)if (verdict.problems.length > 0) {process.stderr.write('[E2E-GATE] The EvenDrive drag-and-drop gate did NOT pass:\n')for (const problem of verdict.problems) process.stderr.write(` - ${problem}\n`)diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex c129ea928..6f440d7b7 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.752",+ "version": "0.1.753","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.752",+ "version": "0.1.753","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 8aae36021..1e161a87d 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.752",+ "version": "0.1.753","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/control-ui/test/__tests__/gfsDragAndDropGate.test.ts b/control-ui/test/__tests__/gfsDragAndDropGate.test.tsindex aa7c06676..ae73c1836 100644--- a/control-ui/test/__tests__/gfsDragAndDropGate.test.ts+++ b/control-ui/test/__tests__/gfsDragAndDropGate.test.ts@@ -1,17 +1,24 @@import { describe, expect, it } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'import {ADMIN_PASSWORD_KEYS,ADMIN_USER_KEYS,CONFIRM_MUTATIONS_FLAG,collectGateProblems,+ collectReportJourneys,evaluateGateReport,+ tallyReportJourneys,+ writeSanitizedRunSummary,} from '../../e2e/run-gfs-drag-and-drop.mjs'/*** The EvenDrive drag-and-drop gate is the frontend-owned entry point that- * makes a missing setup LOUD. These regressions pin the two halves of that- * contract: the gate refuses to run without the required setup, and it never- * reads a zero-journey or skipped-journey run as a green result.+ * makes a missing setup LOUD. These regressions pin the three halves of that+ * contract: the gate refuses to run without the required setup, it never+ * reads a zero-journey or skipped-journey run as a green result, and it+ * never reads an INCOMPLETE report as one.*/const completeSetup = {@@ -22,6 +29,51 @@ const completeSetup = {CONTROL_API_URL: 'http://127.0.0.1:8090',}+type Outcome = 'expected' | 'skipped' | 'unexpected' | 'flaky'++const LANE = 'control-ui'+const COMMAND = 'npm run e2e:gfs-drag-and-drop'+const FILE = 'gfs-drag-and-drop.spec.ts'++/**+ * A report shaped like the one Playwright writes: the suite tree with one+ * spec per journey, and the counters that summarise it.+ */+function journeyReport(+ journeys: Array<{ title: string; outcome?: Outcome | null; results?: number }>,+ counterOverrides: Record<string, unknown> = {}+) {+ const stats = { expected: 0, skipped: 0, unexpected: 0, flaky: 0, ...counterOverrides }+ for (const journey of journeys) {+ const outcome = journey.outcome ?? 'expected'+ if (outcome in stats) stats[outcome] += 1+ }+ return {+ suites: [+ {+ title: FILE,+ file: FILE,+ specs: journeys.map(journey => ({+ title: journey.title,+ file: FILE,+ tests: [+ {+ ...(journey.outcome === null ? {} : { status: journey.outcome ?? 'expected' }),+ expectedStatus: 'passed',+ results:+ journey.results === undefined+ ? [{ status: journey.outcome === 'skipped' ? 'skipped' : 'passed' }]+ : Array.from({ length: journey.results }, () => ({ status: 'passed' })),+ },+ ],+ })),+ suites: [],+ },+ ],+ stats,+ }+}+describe('EvenDrive drag-and-drop E2E gate', () => {describe('required setup', () => {it('accepts a complete setup', () => {@@ -73,7 +125,7 @@ describe('EvenDrive drag-and-drop E2E gate', () => {})describe('run verdict', () => {- const passingReport = { stats: { expected: 2, skipped: 0, unexpected: 0, flaky: 0 } }+ const passingReport = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])it.each([{ status: 1 },@@ -91,38 +143,182 @@ describe('EvenDrive drag-and-drop E2E gate', () => {})it('rejects flaky journeys', () => {- const report = { stats: { ...passingReport.stats, flaky: 1 } }+ const report = journeyReport([{ title: 'journey one', outcome: 'flaky' }])expect(evaluateGateReport(report).problems.join('\n')).toContain('flaky')})it('rejects malformed result counts', () => {- const report = { stats: { ...passingReport.stats, skipped: 'invalid' } }+ const report = journeyReport([{ title: 'journey one' }], { skipped: 'invalid' })expect(evaluateGateReport(report).problems.join('\n')).toContain('invalid result counts')})it('treats a run that executed zero journeys as a failure', () => {- const verdict = evaluateGateReport({ stats: { expected: 0, skipped: 7, unexpected: 0 } })+ const verdict = evaluateGateReport(+ journeyReport([{ title: 'journey one', outcome: 'skipped' }])+ )expect(verdict.problems.join('\n')).toContain('executed zero journeys')})it('treats a skipped journey as a failure', () => {- const verdict = evaluateGateReport({ stats: { expected: 3, skipped: 1, unexpected: 0 } })+ const verdict = evaluateGateReport(+ journeyReport([{ title: 'journey one' }, { title: 'journey two', outcome: 'skipped' }])+ )expect(verdict.problems.join('\n')).toContain('skipped')})it('treats a failed journey as a failure', () => {- const verdict = evaluateGateReport({ stats: { expected: 3, skipped: 0, unexpected: 1 } })+ const verdict = evaluateGateReport(+ journeyReport([{ title: 'journey one' }, { title: 'journey two', outcome: 'unexpected' }])+ )expect(verdict.problems.join('\n')).toContain('failed')})it('accepts a clean run', () => {- const verdict = evaluateGateReport({ stats: { expected: 7, skipped: 0, unexpected: 0 } })+ const verdict = evaluateGateReport(passingReport)expect(verdict.problems).toEqual([])- expect(verdict.stats.expected).toBe(7)+ expect(verdict.stats.expected).toBe(2)})it('treats a missing report as a failure', () => {expect(evaluateGateReport(undefined).problems.join('\n')).toContain('executed zero journeys')})})++ describe('incomplete reports', () => {+ it('rejects a report whose counters are incomplete', () => {+ // The reproduced defect: the missing counters used to be read as+ // successful zero counts.+ const verdict = evaluateGateReport({ stats: { expected: 1 } }, { status: 0 })+ expect(verdict.problems.length).toBeGreaterThan(0)+ expect(verdict.problems.join('\n')).toContain('invalid result counts')+ })++ it('rejects a report that lists no journeys', () => {+ const verdict = evaluateGateReport({+ stats: { expected: 1, skipped: 0, unexpected: 0, flaky: 0 },+ })+ expect(verdict.problems.join('\n')).toContain('lists no journeys')+ })++ it('rejects a report whose counters do not reconcile with its inventory', () => {+ const report = journeyReport([{ title: 'journey one' }], { expected: 5 })+ expect(evaluateGateReport(report).problems.join('\n')).toContain('does not reconcile')+ })++ it('rejects a journey the report carries no outcome for', () => {+ const report = journeyReport([{ title: 'journey one', outcome: null }])+ const problems = evaluateGateReport(report).problems.join('\n')+ expect(problems).toContain('carry no outcome')+ })++ it('rejects a journey whose recorded outcome contradicts the counters', () => {+ // Playwright counts a journey with no result as skipped; a report that+ // claims otherwise does not reconcile.+ const report = journeyReport([{ title: 'journey one', results: 0 }])+ expect(evaluateGateReport(report).problems.join('\n')).toContain('does not reconcile')+ })++ it('rejects a report that is missing a selected journey', () => {+ const selected = collectReportJourneys(+ journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ )+ const report = journeyReport([{ title: 'journey one' }])+ expect(evaluateGateReport(report, { status: 0 }, selected).problems.join('\n')).toContain(+ 'missing 1 selected journey'+ )+ })++ it('rejects a report that carries a journey that was not selected', () => {+ const selected = collectReportJourneys(journeyReport([{ title: 'journey one' }]))+ const report = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ expect(evaluateGateReport(report, { status: 0 }, selected).problems.join('\n')).toContain(+ 'not selected'+ )+ })++ it('accepts a report that matches the selected journeys exactly', () => {+ const report = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ const selected = collectReportJourneys(report)+ expect(evaluateGateReport(report, { status: 0 }, selected).problems).toEqual([])+ })+ })++ describe('sanitized run summary', () => {+ it('binds the revision, the selected cases, the outcomes and the exit code', () => {+ const filePath = path.join(os.tmpdir(), `gfs-dnd-summary-${LANE}.json`)+ const report = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ const summary = writeSanitizedRunSummary({+ lane: LANE,+ revision: 'abc123',+ branch: 'feat/example',+ command: COMMAND,+ report,+ run: { status: 0 },+ selectedJourneys: collectReportJourneys(report),+ verdict: 'pass',+ filePath,+ })++ expect(summary).toMatchObject({+ lane: LANE,+ revision: 'abc123',+ branch: 'feat/example',+ command: COMMAND,+ processExit: 0,+ verdict: 'pass',+ })+ expect(summary.selected).toEqual(['journey one', 'journey two'])+ expect(summary.journeys).toEqual([+ { title: 'journey one', status: 'expected' },+ { title: 'journey two', status: 'expected' },+ ])+ expect(JSON.parse(fs.readFileSync(filePath, 'utf8'))).toEqual(summary)+ fs.rmSync(filePath, { force: true })+ })++ it('does not carry the raw report text into the summary', () => {+ const filePath = path.join(os.tmpdir(), `gfs-dnd-summary-private-${LANE}.json`)+ const report = {+ ...journeyReport([{ title: 'journey one', outcome: 'unexpected' }]),+ errors: [{ message: 'the upstream said: private-token-value' }],+ }+ const summary = writeSanitizedRunSummary({+ lane: LANE,+ revision: 'abc123',+ branch: 'feat/example',+ command: COMMAND,+ report,+ run: { status: 1 },+ selectedJourneys: collectReportJourneys(report),+ verdict: 'fail',+ filePath,+ })++ expect(JSON.stringify(summary)).not.toContain('private-token-value')+ expect(summary.processExit).toBe(1)+ expect(summary.verdict).toBe('fail')+ fs.rmSync(filePath, { force: true })+ })+ })++ describe('report inventory', () => {+ it('identifies a journey by its file and title path', () => {+ const journeys = collectReportJourneys(journeyReport([{ title: 'journey one' }]))+ expect(journeys).toHaveLength(1)+ expect(journeys[0]?.identity).toBe(`${FILE}::journey one`)+ })++ it('tallies the outcomes the way Playwright does', () => {+ const journeys = collectReportJourneys(+ journeyReport([{ title: 'one' }, { title: 'two' }, { title: 'three', outcome: 'skipped' }])+ )+ expect(tallyReportJourneys(journeys)).toEqual({+ expected: 2,+ skipped: 1,+ unexpected: 0,+ flaky: 0,+ incomplete: 0,+ })+ })+ })})diff --git a/desktop-app/test/__tests__/gfsDragAndDropGate.test.ts b/desktop-app/test/__tests__/gfsDragAndDropGate.test.tsindex 61fb3f879..12728d54c 100644--- a/desktop-app/test/__tests__/gfsDragAndDropGate.test.ts+++ b/desktop-app/test/__tests__/gfsDragAndDropGate.test.ts@@ -1,10 +1,15 @@import { afterEach, describe, expect, it, vi } from 'vitest'import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'import {DESKTOP_EMAIL_KEYS,DESKTOP_PASSWORD_KEYS,collectGateProblems,+ collectReportJourneys,evaluateGateReport,+ tallyReportJourneys,+ writeSanitizedRunSummary,} from '../e2e-playwright/run-gfs-drag-and-drop.mjs'/**@@ -14,6 +19,51 @@ import {* reads a zero-journey or skipped-journey run as a green result.*/+type Outcome = 'expected' | 'skipped' | 'unexpected' | 'flaky'++const LANE = 'desktop-app'+const COMMAND = 'npm run test:e2e:playwright:gfs-drag-and-drop'+const FILE = 'gfs-drag-and-drop-desktop.test.ts'++/**+ * A report shaped like the one Playwright writes: the suite tree with one+ * spec per journey, and the counters that summarise it.+ */+function journeyReport(+ journeys: Array<{ title: string; outcome?: Outcome | null; results?: number }>,+ counterOverrides: Record<string, unknown> = {}+) {+ const stats = { expected: 0, skipped: 0, unexpected: 0, flaky: 0, ...counterOverrides }+ for (const journey of journeys) {+ const outcome = journey.outcome ?? 'expected'+ if (outcome in stats) stats[outcome] += 1+ }+ return {+ suites: [+ {+ title: FILE,+ file: FILE,+ specs: journeys.map(journey => ({+ title: journey.title,+ file: FILE,+ tests: [+ {+ ...(journey.outcome === null ? {} : { status: journey.outcome ?? 'expected' }),+ expectedStatus: 'passed',+ results:+ journey.results === undefined+ ? [{ status: journey.outcome === 'skipped' ? 'skipped' : 'passed' }]+ : Array.from({ length: journey.results }, () => ({ status: 'passed' })),+ },+ ],+ })),+ suites: [],+ },+ ],+ stats,+ }+}+const completeSetup = {E2E_K8S_CONTEXT: 'dev',E2E_ALLOWED_CONTEXTS: 'dev',@@ -81,7 +131,7 @@ describe('EvenDrive drag-and-drop Desktop E2E gate', () => {})describe('run verdict', () => {- const passingReport = { stats: { expected: 2, skipped: 0, unexpected: 0, flaky: 0 } }+ const passingReport = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])it.each([{ status: 1 },@@ -99,32 +149,41 @@ describe('EvenDrive drag-and-drop Desktop E2E gate', () => {})it('rejects flaky journeys', () => {- const report = { stats: { ...passingReport.stats, flaky: 1 } }+ const report = journeyReport([{ title: 'journey one', outcome: 'flaky' }])expect(evaluateGateReport(report).problems.join('\n')).toContain('flaky')})it('rejects malformed result counts', () => {- const report = { stats: { ...passingReport.stats, skipped: 'invalid' } }+ const report = journeyReport([{ title: 'journey one' }], { skipped: 'invalid' })expect(evaluateGateReport(report).problems.join('\n')).toContain('invalid result counts')})it('treats a run that executed zero journeys as a failure', () => {- const verdict = evaluateGateReport({ stats: { expected: 0, skipped: 2, unexpected: 0 } })+ const verdict = evaluateGateReport(+ journeyReport([+ { title: 'journey one', outcome: 'skipped' },+ { title: 'journey two', outcome: 'skipped' },+ ])+ )expect(verdict.problems.join('\n')).toContain('executed zero journeys')})it('treats a skipped journey as a failure', () => {- const verdict = evaluateGateReport({ stats: { expected: 2, skipped: 1, unexpected: 0 } })+ const verdict = evaluateGateReport(+ journeyReport([{ title: 'journey one' }, { title: 'journey two', outcome: 'skipped' }])+ )expect(verdict.problems.join('\n')).toContain('skipped')})it('treats a failed journey as a failure', () => {- const verdict = evaluateGateReport({ stats: { expected: 2, skipped: 0, unexpected: 1 } })+ const verdict = evaluateGateReport(+ journeyReport([{ title: 'journey one' }, { title: 'journey two', outcome: 'unexpected' }])+ )expect(verdict.problems.join('\n')).toContain('failed')})it('accepts a clean run', () => {- const verdict = evaluateGateReport({ stats: { expected: 2, skipped: 0, unexpected: 0 } })+ const verdict = evaluateGateReport(passingReport)expect(verdict.problems).toEqual([])expect(verdict.stats.expected).toBe(2)})@@ -133,4 +192,139 @@ describe('EvenDrive drag-and-drop Desktop E2E gate', () => {expect(evaluateGateReport(undefined).problems.join('\n')).toContain('executed zero journeys')})})++ describe('incomplete reports', () => {+ it('rejects a report whose counters are incomplete', () => {+ // The reproduced defect: the missing counters used to be read as+ // successful zero counts.+ const verdict = evaluateGateReport({ stats: { expected: 1 } }, { status: 0 })+ expect(verdict.problems.length).toBeGreaterThan(0)+ expect(verdict.problems.join('\n')).toContain('invalid result counts')+ })++ it('rejects a report that lists no journeys', () => {+ const verdict = evaluateGateReport({+ stats: { expected: 1, skipped: 0, unexpected: 0, flaky: 0 },+ })+ expect(verdict.problems.join('\n')).toContain('lists no journeys')+ })++ it('rejects a report whose counters do not reconcile with its inventory', () => {+ const report = journeyReport([{ title: 'journey one' }], { expected: 5 })+ expect(evaluateGateReport(report).problems.join('\n')).toContain('does not reconcile')+ })++ it('rejects a journey the report carries no outcome for', () => {+ const report = journeyReport([{ title: 'journey one', outcome: null }])+ expect(evaluateGateReport(report).problems.join('\n')).toContain('carry no outcome')+ })++ it('rejects a journey whose recorded outcome contradicts the counters', () => {+ const report = journeyReport([{ title: 'journey one', results: 0 }])+ expect(evaluateGateReport(report).problems.join('\n')).toContain('does not reconcile')+ })++ it('rejects a report that is missing a selected journey', () => {+ const selected = collectReportJourneys(+ journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ )+ const report = journeyReport([{ title: 'journey one' }])+ expect(evaluateGateReport(report, { status: 0 }, selected).problems.join('\n')).toContain(+ 'missing 1 selected journey'+ )+ })++ it('rejects a report that carries a journey that was not selected', () => {+ const selected = collectReportJourneys(journeyReport([{ title: 'journey one' }]))+ const report = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ expect(evaluateGateReport(report, { status: 0 }, selected).problems.join('\n')).toContain(+ 'not selected'+ )+ })++ it('accepts a report that matches the selected journeys exactly', () => {+ const report = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ const selected = collectReportJourneys(report)+ expect(evaluateGateReport(report, { status: 0 }, selected).problems).toEqual([])+ })+ })++ describe('sanitized run summary', () => {+ it('binds the revision, the selected cases, the outcomes and the exit code', () => {+ const filePath = path.join(os.tmpdir(), `gfs-dnd-summary-${LANE}.json`)+ const report = journeyReport([{ title: 'journey one' }, { title: 'journey two' }])+ const summary = writeSanitizedRunSummary({+ lane: LANE,+ revision: 'abc123',+ branch: 'feat/example',+ command: COMMAND,+ report,+ run: { status: 0 },+ selectedJourneys: collectReportJourneys(report),+ verdict: 'pass',+ filePath,+ })++ expect(summary).toMatchObject({+ lane: LANE,+ revision: 'abc123',+ branch: 'feat/example',+ command: COMMAND,+ processExit: 0,+ verdict: 'pass',+ })+ expect(summary.selected).toEqual(['journey one', 'journey two'])+ expect(summary.journeys).toEqual([+ { title: 'journey one', status: 'expected' },+ { title: 'journey two', status: 'expected' },+ ])+ expect(JSON.parse(fs.readFileSync(filePath, 'utf8'))).toEqual(summary)+ fs.rmSync(filePath, { force: true })+ })++ it('does not carry the raw report text into the summary', () => {+ const filePath = path.join(os.tmpdir(), `gfs-dnd-summary-private-${LANE}.json`)+ const report = {+ ...journeyReport([{ title: 'journey one', outcome: 'unexpected' }]),+ errors: [{ message: 'the upstream said: private-token-value' }],+ }+ const summary = writeSanitizedRunSummary({+ lane: LANE,+ revision: 'abc123',+ branch: 'feat/example',+ command: COMMAND,+ report,+ run: { status: 1 },+ selectedJourneys: collectReportJourneys(report),+ verdict: 'fail',+ filePath,+ })++ expect(JSON.stringify(summary)).not.toContain('private-token-value')+ expect(summary.processExit).toBe(1)+ expect(summary.verdict).toBe('fail')+ fs.rmSync(filePath, { force: true })+ })+ })++ describe('report inventory', () => {+ it('identifies a journey by its file and title path', () => {+ const journeys = collectReportJourneys(journeyReport([{ title: 'journey one' }]))+ expect(journeys).toHaveLength(1)+ expect(journeys[0]?.identity).toBe(`${FILE}::journey one`)+ })++ it('tallies the outcomes the way Playwright does', () => {+ const journeys = collectReportJourneys(+ journeyReport([{ title: 'one' }, { title: 'two' }, { title: 'three', outcome: 'skipped' }])+ )+ expect(tallyReportJourneys(journeys)).toEqual({+ expected: 2,+ skipped: 1,+ unexpected: 0,+ flaky: 0,+ incomplete: 0,+ })+ })+ })})diff --git a/desktop-app/test/e2e-playwright/run-gfs-drag-and-drop.mjs b/desktop-app/test/e2e-playwright/run-gfs-drag-and-drop.mjsindex 35615b8ea..b02661b82 100644--- a/desktop-app/test/e2e-playwright/run-gfs-drag-and-drop.mjs+++ b/desktop-app/test/e2e-playwright/run-gfs-drag-and-drop.mjs@@ -28,7 +28,7 @@//// Exit codes: 0 = every requested journey ran and passed. 1 = the gate// refused to run, or the journey result was not a clean pass.-import { spawnSync } from 'node:child_process'+import { execFileSync, spawnSync } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'@@ -50,6 +50,13 @@ export const DESKTOP_EMAIL_KEYS = []const PROBE_TIMEOUT_MS = 10_000+const PLAYWRIGHT_ARGS = [+ 'test',+ '--config=test/e2e-playwright/playwright.config.ts',+ 'gfs-drag-and-drop-desktop.test.ts',+ '--project=default',+ '--workers=1',+]/** First non-empty value among the candidate env names (never logged). */export function firstConfiguredValue(env, keys) {@@ -135,12 +142,82 @@ export function collectGateProblems(env) {return problems}+/**+ * The counters a Playwright JSON report must carry. A report without them is+ * INCOMPLETE: a missing counter is not "zero journeys", it is unknown, and+ * an unknown count can never certify a run.+ */+export const REQUIRED_REPORT_COUNTERS = ['expected', 'skipped', 'unexpected', 'flaky']++/**+ * Every journey a Playwright JSON report lists, with the outcome Playwright+ * recorded for it.+ *+ * The inventory is what makes a report verifiable: the counters are only a+ * summary of it, and a summary that does not match the detail it summarises+ * is not evidence. A journey with no recorded outcome is an incomplete+ * report.+ */+export function collectReportJourneys(report) {+ const journeys = []+ const walk = (suite, path) => {+ const title = typeof suite?.title === 'string' ? suite.title : ''+ const file = typeof suite?.file === 'string' ? suite.file : ''+ // The file-level suite repeats the file name; it is not part of a test's+ // title path.+ const nextPath = title && title !== file ? [...path, title] : path+ for (const spec of suite?.specs ?? []) {+ for (const test of spec?.tests ?? []) {+ const specTitle = String(spec?.title ?? '')+ journeys.push({+ identity: `${String(spec?.file ?? '')}::${[...nextPath, specTitle].join(' › ')}`,+ title: specTitle,+ file: String(spec?.file ?? ''),+ outcome: typeof test?.status === 'string' ? test.status : null,+ results: Array.isArray(test?.results) ? test.results.length : 0,+ })+ }+ }+ for (const child of suite?.suites ?? []) walk(child, nextPath)+ }+ for (const suite of report?.suites ?? []) walk(suite, [])+ return journeys+}++/**+ * The outcome tally of a report's inventory, computed the way Playwright+ * computes it (a journey with no result counts as skipped). A journey with an+ * outcome Playwright does not report is INCOMPLETE.+ */+export function tallyReportJourneys(journeys) {+ const tally = { expected: 0, skipped: 0, unexpected: 0, flaky: 0, incomplete: 0 }+ for (const journey of journeys) {+ const outcome = journey.results === 0 ? 'skipped' : journey.outcome+ if (+ outcome === 'expected' ||+ outcome === 'skipped' ||+ outcome === 'unexpected' ||+ outcome === 'flaky'+ ) {+ tally[outcome] += 1+ continue+ }+ tally.incomplete += 1+ }+ return tally+}+/*** The verdict of a Playwright JSON report. A run is a clean pass only when- * at least one journey actually executed, nothing was skipped, and nothing- * failed. A report that ran zero journeys is NOT a pass.+ * the report is COMPLETE, at least one journey actually executed, nothing+ * was skipped, and nothing failed.+ *+ * `selectedJourneys` is the inventory Playwright selected before the run (the+ * `--list` pass). When it is supplied, the report must describe exactly that+ * set: a report that lists fewer journeys than were selected is not evidence+ * for the run.*/-export function evaluateGateReport(report, run = { status: 0 }) {+export function evaluateGateReport(report, run = { status: 0 }, selectedJourneys = null) {const problems = []if (run.error || run.signal || run.status !== 0) {problems.push('Playwright did not exit successfully. The report cannot certify this run.')@@ -149,12 +226,64 @@ export function evaluateGateReport(report, run = { status: 0 }) {problems.push('Playwright reported a run-level error. The report cannot certify this run.')}const stats = report && typeof report === 'object' ? (report.stats ?? {}) : {}- const expected = Number(stats.expected ?? 0)- const skipped = Number(stats.skipped ?? 0)- const unexpected = Number(stats.unexpected ?? 0)- const flaky = Number(stats.flaky ?? 0)+ const counters = {}+ for (const key of REQUIRED_REPORT_COUNTERS) {+ const value = stats[key]+ if (!Number.isInteger(value) || value < 0) {+ problems.push(+ `The journey report has invalid result counts: "${key}" is missing or not a non-negative integer. ` ++ 'An incomplete report cannot certify this run.'+ )+ counters[key] = null+ continue+ }+ counters[key] = value+ }+ const expected = counters.expected ?? 0+ const skipped = counters.skipped ?? 0+ const unexpected = counters.unexpected ?? 0+ const flaky = counters.flaky ?? 0- if (!Number.isFinite(expected) || expected <= 0) {+ const journeys = collectReportJourneys(report)+ const tally = tallyReportJourneys(journeys)+ if (journeys.length === 0) {+ problems.push(+ 'The journey report lists no journeys. A report without its inventory cannot certify this run.'+ )+ }+ if (tally.incomplete > 0) {+ problems.push(+ `${tally.incomplete} journey(s) in the report carry no outcome. The report is incomplete.`+ )+ }+ const mismatched = REQUIRED_REPORT_COUNTERS.filter(+ key => counters[key] !== null && counters[key] !== tally[key]+ )+ if (mismatched.length > 0) {+ problems.push(+ `The journey report does not reconcile with its own inventory: ${mismatched.join(', ')} ` ++ `(report ${expected}/${skipped}/${unexpected}/${flaky}, ` ++ `inventory ${tally.expected}/${tally.skipped}/${tally.unexpected}/${tally.flaky}).`+ )+ }+ if (selectedJourneys) {+ const selected = new Set(selectedJourneys.map(journey => journey.identity))+ const reported = new Set(journeys.map(journey => journey.identity))+ const missing = [...selected].filter(identity => !reported.has(identity))+ const extra = [...reported].filter(identity => !selected.has(identity))+ if (missing.length > 0) {+ problems.push(+ `The journey report is missing ${missing.length} selected journey(s): ${missing.join(', ')}`+ )+ }+ if (extra.length > 0) {+ problems.push(+ `The journey report contains ${extra.length} journey(s) that were not selected: ${extra.join(', ')}`+ )+ }+ }++ if (expected <= 0) {problems.push('The journey suite executed zero journeys. A skipped suite is not a green result: ' +'check the Kubernetes context, the Desktop credential and the endpoint configuration.'@@ -163,17 +292,6 @@ export function evaluateGateReport(report, run = { status: 0 }) {if (skipped > 0) {problems.push(`${skipped} journey(s) were skipped. A skipped journey is not a green result.`)}- if (- !Number.isInteger(skipped) ||- skipped < 0 ||- !Number.isInteger(unexpected) ||- unexpected < 0 ||- !Number.isInteger(flaky) ||- flaky < 0 ||- !Number.isInteger(expected)- ) {- problems.push('The journey report has invalid result counts.')- }if (unexpected > 0) {problems.push(`${unexpected} journey(s) failed.`)}@@ -184,6 +302,52 @@ export function evaluateGateReport(report, run = { status: 0 }) {return { problems, stats: { expected, skipped, unexpected, flaky } }}+/**+ * The SANITIZED evidence file for this run: the tested revision, the+ * selected journeys, their outcomes and the process exit.+ *+ * The raw Playwright report carries error text, stdout and attachments, so+ * it stays private under the ignored artifact directory. This file is the+ * part a reviewer can read: no credentials, no cookies, no auth headers, no+ * request or response bodies — only what certifies WHICH journeys ran, on+ * WHICH revision, with WHICH exit code.+ */+export function writeSanitizedRunSummary({+ lane,+ revision,+ branch,+ command,+ report,+ run,+ selectedJourneys,+ verdict,+ filePath,+}) {+ const journeys = collectReportJourneys(report).map(journey => ({+ title: journey.title,+ status: journey.outcome ?? 'incomplete',+ }))+ const summary = {+ lane,+ revision,+ branch,+ command,+ processExit: typeof run?.status === 'number' ? run.status : null,+ signal: run?.signal ?? null,+ verdict,+ counts: {+ expected: Number(report?.stats?.expected ?? 0),+ skipped: Number(report?.stats?.skipped ?? 0),+ unexpected: Number(report?.stats?.unexpected ?? 0),+ flaky: Number(report?.stats?.flaky ?? 0),+ },+ selected: (selectedJourneys ?? []).map(journey => journey.title),+ journeys,+ }+ fs.writeFileSync(filePath, `${JSON.stringify(summary, null, 2)}\n`)+ return summary+}+/** Bounded reachability probe. Never prints the response body. */export async function probeReachable(url, timeoutMs = PROBE_TIMEOUT_MS) {try {@@ -198,6 +362,26 @@ export async function probeReachable(url, timeoutMs = PROBE_TIMEOUT_MS) {}}+/** The revision the lane ran against (never a branch guess). */+export function readTestedRevision(repoRoot) {+ try {+ return execFileSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()+ } catch {+ return 'unknown'+ }+}++/** The branch the lane ran on. */+export function readTestedBranch(repoRoot) {+ try {+ return execFileSync('git', ['-C', repoRoot, 'rev-parse', '--abbrev-ref', 'HEAD'], {+ encoding: 'utf8',+ }).trim()+ } catch {+ return 'unknown'+ }+}+function resolvePlaywrightBin() {const bin = path.join(APP_ROOT,@@ -247,30 +431,59 @@ async function main() {const dir = artifactDir()const reportPath = path.join(dir, 'playwright-report.json')+ const selectionPath = path.join(dir, 'playwright-selection.json')const playwrightBin = resolvePlaywrightBin()// A previous successful run must never supply evidence for a failed launch.fs.rmSync(reportPath, { force: true })+ fs.rmSync(selectionPath, { force: true })++ // Enumerate the journeys Playwright SELECTS before running them. The run's+ // report is reconciled against this inventory, so a report that describes+ // fewer journeys than were selected cannot certify the run.+ process.stdout.write('[E2E-GATE] enumerating the selected journeys\n')+ const selection = spawnSync(playwrightBin, [...PLAYWRIGHT_ARGS, '--list', '--reporter=json'], {+ cwd: APP_ROOT,+ stdio: 'inherit',+ timeout: 10 * 60_000,+ env: { ...env, PLAYWRIGHT_JSON_OUTPUT_NAME: selectionPath },+ })+ if (selection.status !== 0 || !fs.existsSync(selectionPath)) {+ process.stderr.write(+ '[E2E-GATE] Playwright could not enumerate the selected journeys. ' ++ 'The gate cannot certify this run.\n'+ )+ return 1+ }+ let selectedJourneys+ try {+ selectedJourneys = collectReportJourneys(JSON.parse(fs.readFileSync(selectionPath, 'utf8')))+ } catch (error) {+ process.stderr.write(+ `[E2E-GATE] The Playwright selection report is unreadable: ${error instanceof Error ? error.message : String(error)}\n`+ )+ return 1+ }+ if (selectedJourneys.length === 0) {+ process.stderr.write(+ '[E2E-GATE] Playwright selected no journeys. The gate cannot certify this run.\n'+ )+ return 1+ }+ process.stdout.write(+ `[E2E-GATE] ${selectedJourneys.length} journey(s) selected: ${selectedJourneys+ .map(journey => journey.title)+ .join(' | ')}\n`+ )process.stdout.write(`[E2E-GATE] running the EvenDrive drag-and-drop journeys (report: ${reportPath})\n`)- const run = spawnSync(- playwrightBin,- [- 'test',- '--config=test/e2e-playwright/playwright.config.ts',- 'gfs-drag-and-drop-desktop.test.ts',- '--project=default',- '--workers=1',- '--reporter=list,json',- ],- {- cwd: APP_ROOT,- stdio: 'inherit',- timeout: 75 * 60_000,- env: { ...env, PLAYWRIGHT_JSON_OUTPUT_NAME: reportPath },- }- )+ const run = spawnSync(playwrightBin, [...PLAYWRIGHT_ARGS, '--reporter=list,json'], {+ cwd: APP_ROOT,+ stdio: 'inherit',+ timeout: 75 * 60_000,+ env: { ...env, PLAYWRIGHT_JSON_OUTPUT_NAME: reportPath },+ })if (!fs.existsSync(reportPath)) {process.stderr.write(@@ -289,7 +502,20 @@ async function main() {return 1}- const verdict = evaluateGateReport(report, run)+ const verdict = evaluateGateReport(report, run, selectedJourneys)+ const summaryPath = path.join(dir, 'playwright-summary.json')+ writeSanitizedRunSummary({+ lane: 'desktop-app',+ revision: readTestedRevision(REPO_ROOT),+ branch: readTestedBranch(REPO_ROOT),+ command: 'npm run test:e2e:playwright:gfs-drag-and-drop',+ report,+ run,+ selectedJourneys,+ verdict: verdict.problems.length > 0 ? 'fail' : 'pass',+ filePath: summaryPath,+ })+ process.stdout.write(`[E2E-GATE] sanitized summary: ${summaryPath}\n`)if (verdict.problems.length > 0) {process.stderr.write('[E2E-GATE] The EvenDrive drag-and-drop gate did NOT pass:\n')for (const problem of verdict.problems) process.stderr.write(` - ${problem}\n`)diff --git a/desktop-app/ui/src/gfs/__tests__/dragAdjudication.test.tsx b/desktop-app/ui/src/gfs/__tests__/dragAdjudication.test.tsxindex 0b491f4df..79f1d9d7b 100644--- a/desktop-app/ui/src/gfs/__tests__/dragAdjudication.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/dragAdjudication.test.tsx@@ -272,6 +272,24 @@ describe('useGfsDragAdjudication — required-probe drop admission (R1-H1)', ()expect(decision.allowNumberedRename).toBe(false)}})++ it('refuses the drop when the OPTIONAL rename probe reports a session failure', async () => {+ // The rename probe is optional for the MOVE, so an ordinary failure only+ // withdraws the rename option. A session failure is not ordinary: the+ // session the move would be dispatched with is gone, so the drop must be+ // refused terminally instead of being dispatched into a dead session.+ const message = await affordancesFailureMessage(401)+ probes = await grantedProbes({ 'src-1': { error: new Error(message) } })+ const handleAuthorityFailure = vi.fn(() => true)+ const { result } = renderAdjudication(handleAuthorityFailure)++ const decision = await result.current.adjudicateDrop(dragSource(), dropTarget())++ expect(decision).toEqual({ allowed: false, reason: 'session-lost' })+ // The surface is told the session is gone, so it revokes instead of+ // leaving an active session over a dead one.+ expect(handleAuthorityFailure).toHaveBeenCalled()+ })})describe('useGfsDragAdjudication — the rename probe reads a fresh observation (RP-023)', () => {diff --git a/desktop-app/ui/src/gfs/dragAdjudication.ts b/desktop-app/ui/src/gfs/dragAdjudication.tsindex 5d7221ff1..8a6ecc886 100644--- a/desktop-app/ui/src/gfs/dragAdjudication.ts+++ b/desktop-app/ui/src/gfs/dragAdjudication.ts@@ -457,7 +457,22 @@ export function useGfsDragAdjudication(deps: GfsDragAdjudicationDeps) {// Rename capability (not user consent): source-resource write proves a// combined rename+move; the folder confirmation records the opt-in.+ //+ // This probe is OPTIONAL for the move, so an ordinary failure only+ // withdraws the rename option and the move stays allowed. A SESSION+ // failure is different: the session the move would be dispatched with+ // is gone, so the drop must be refused terminally instead of being+ // dispatched into a dead session. The probe itself already reported the+ // failure to the surface (which revoked the session), so this only+ // CLASSIFIES it.const sourceProbe = await fetchAffordances(source.resourceId, AFFORDANCES_MUTATION_STALE_MS)+ if (!sourceProbe.ok) {+ const message =+ sourceProbe.error instanceof Error ? sourceProbe.error.message : String(sourceProbe.error)+ if (isGfsSessionAuthorityFailure(message, 'operation')) {+ return { allowed: false, reason: 'session-lost' }+ }+ }const canRename = sourceProbe.ok && sourceProbe.held.includes('write')return {diff --git a/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts b/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.tsindex b06c4236b..d4204db18 100644--- a/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts+++ b/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts@@ -5,6 +5,11 @@ import { QueryClient, QueryObserver } from '@tanstack/react-query'import { desktopQueryKeys } from '@hooks/domain/queryKeys'import { markPluginGfsPreviewUnavailable } from '../gfsEntityChangeState'import { applyMoveConvergence, collectKnownChildParents } from '../gfsEntityChangeState'+import {+ ancestryDependentGfsResourceIds,+ publishGfsOpenLocation,+ readGfsOpenLocations,+} from '../gfsOpenLocations'describe('plugin preview unavailable reconciliation', () => {it('increments the reload identity once and preserves it on repeated invalidation', () => {@@ -153,6 +158,68 @@ describe('applyMoveConvergence', () => {unsubscribe()})+ it("re-reads a descendant's ACL rows after a SECOND move, through the relocated chain", async () => {+ // TWO controllers: Files has the leaf L open (reached BY URI, so no+ // children listing connects A to it), the sidebar has B open. The first+ // move (A under B) relocates the leaf's published chain; the second+ // move (of B) must then see the leaf as a descendant — neither the+ // registry's old crumbs nor the children cache could answer that.+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ publishGfsOpenLocation(queryClient, SCOPE, 'files', {+ resourceId: 'L',+ ancestorResourceIds: ['A', 'X', 'root'],+ })+ publishGfsOpenLocation(queryClient, SCOPE, 'sidebar', {+ resourceId: 'B',+ ancestorResourceIds: ['P', 'root'],+ })++ const leafKey = desktopQueryKeys.gfsInheritedAccess(SCOPE, 'L', DRIVE)+ let leafReads = 0+ const observer = new QueryObserver(queryClient, {+ queryKey: leafKey,+ queryFn: async () => {+ leafReads += 1+ return { items: [], coverage: 'complete' }+ },+ })+ const unsubscribe = observer.subscribe(() => {})+ await vi.waitFor(() =>+ expect(queryClient.getQueryCache().find({ queryKey: leafKey })?.state.fetchStatus).toBe(+ 'idle'+ )+ )+ const readsBefore = leafReads++ // Move 1: the sidebar moves A under B.+ applyMoveConvergence(queryClient, SCOPE, DRIVE, {+ resourceId: 'A',+ oldParentId: 'X',+ newParentId: 'B',+ })+ await Promise.resolve()++ // The leaf's chain now names B, so the SECOND move claims it.+ const ancestryDependent = ancestryDependentGfsResourceIds(+ readGfsOpenLocations(queryClient, SCOPE),+ 'B'+ )+ expect(ancestryDependent).toContain('L')++ // Move 2: the sidebar moves B elsewhere. The leaf's inherited rows are+ // derived from its ancestry, so they must be re-read.+ applyMoveConvergence(+ queryClient,+ SCOPE,+ DRIVE,+ { resourceId: 'B', oldParentId: 'P', newParentId: 'Q' },+ { ancestryDependentResourceIds: ancestryDependent }+ )++ await vi.waitFor(() => expect(leafReads).toBeGreaterThan(readsBefore))+ unsubscribe()+ })+it('leaves an unrelated open inherited-access query alone', async () => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })const openKey = desktopQueryKeys.gfsInheritedAccess(SCOPE, 'open', DRIVE)diff --git a/desktop-app/ui/src/lib/__tests__/gfsOpenLocations.test.ts b/desktop-app/ui/src/lib/__tests__/gfsOpenLocations.test.tsindex 136551595..8922cba6d 100644--- a/desktop-app/ui/src/lib/__tests__/gfsOpenLocations.test.ts+++ b/desktop-app/ui/src/lib/__tests__/gfsOpenLocations.test.ts@@ -4,8 +4,11 @@ import { desktopQueryKeys } from '@hooks/domain/queryKeys'import {ancestryDependentGfsResourceIds,nextGfsOpenLocationId,+ publishGfsMoveRelocation,publishGfsOpenLocation,readGfsOpenLocations,+ relocateObservedChain,+ relocatePublishedChains,} from '../gfsOpenLocations'const SCOPE = 'test:user-1:team-1'@@ -55,6 +58,66 @@ describe('gfsOpenLocations', () => {expect(ancestryDependentGfsResourceIds(locations, 'unrelated-1')).toEqual([])})+ describe('two controllers, two moves (RP-005)', () => {+ // Files has the leaf L open, reached BY URI: no children listing ever+ // connected A to L, so the registry's observed chain is the only record+ // of it. The sidebar has B open.+ function twoControllers() {+ return {+ files: { resourceId: 'L', ancestorResourceIds: ['A', 'X', 'root'] },+ sidebar: { resourceId: 'B', ancestorResourceIds: ['P', 'root'] },+ }+ }++ it('relocates the chain of a resource below the moved one', () => {+ expect(relocateObservedChain(['A', 'X', 'root'], 'A', 'B', ['P', 'root'])).toEqual([+ 'A',+ 'B',+ 'P',+ 'root',+ ])+ })++ it('leaves a chain that does not contain the moved resource alone', () => {+ expect(relocateObservedChain(['P', 'root'], 'A', 'B', ['P', 'root'])).toEqual(['P', 'root'])+ })++ it('claims the descendant for the SECOND move after the first relocated its chain', () => {+ const afterFirst = relocatePublishedChains(twoControllers(), 'A', 'B')+ // The leaf's chain now names B, so B is one of its ancestors.+ expect(afterFirst.files?.ancestorResourceIds).toEqual(['A', 'B', 'P', 'root'])+ // The leaf is claimed, and so is the sidebar's own open folder: the+ // moved resource itself is always ancestry-dependent.+ expect(ancestryDependentGfsResourceIds(Object.values(afterFirst), 'B')).toEqual(['L', 'B'])+ // A move of B's own parent is claimed too.+ expect(ancestryDependentGfsResourceIds(Object.values(afterFirst), 'P')).toEqual(['L', 'B'])+ })++ it('publishes the relocation into the shared registry', () => {+ const queryClient = new QueryClient()+ publishGfsOpenLocation(queryClient, SCOPE, 'files', {+ resourceId: 'L',+ ancestorResourceIds: ['A', 'X', 'root'],+ })+ publishGfsOpenLocation(queryClient, SCOPE, 'sidebar', {+ resourceId: 'B',+ ancestorResourceIds: ['P', 'root'],+ })++ publishGfsMoveRelocation(queryClient, SCOPE, 'A', 'B')++ expect(readGfsOpenLocations(queryClient, SCOPE)).toEqual([+ { resourceId: 'L', ancestorResourceIds: ['A', 'B', 'P', 'root'] },+ { resourceId: 'B', ancestorResourceIds: ['P', 'root'] },+ ])+ // The second move now claims the leaf (and the sidebar's own open+ // folder, which is the moved resource itself).+ expect(+ ancestryDependentGfsResourceIds(readGfsOpenLocations(queryClient, SCOPE), 'B')+ ).toEqual(['L', 'B'])+ })+ })+it('keeps the registry inside the shared query cache', () => {const queryClient = new QueryClient()publishGfsOpenLocation(queryClient, SCOPE, 'mount-a', {diff --git a/desktop-app/ui/src/lib/gfsEntityChangeState.ts b/desktop-app/ui/src/lib/gfsEntityChangeState.tsindex ead25034a..552ced71e 100644--- a/desktop-app/ui/src/lib/gfsEntityChangeState.ts+++ b/desktop-app/ui/src/lib/gfsEntityChangeState.ts@@ -2,6 +2,7 @@ import type { QueryClient } from '@tanstack/react-query'import { planMoveConvergence } from '@clerum/gfs-interaction-policy'import { desktopQueryKeys } from '@hooks/domain/queryKeys'import { parseHttpStatus } from './gfsGrantErrors'+import { publishGfsMoveRelocation } from './gfsOpenLocations'import { refreshPreviewTab } from './workspaceTabs'import type { WorkspaceTabsState } from './workspaceTabs.types'@@ -125,6 +126,14 @@ export function applyMoveConvergence(const known = { childParentByResourceId: collectKnownChildParents(queryClient, scope, drive) }const plan = planMoveConvergence(receipt, known)+ // The published open-location chains are OBSERVED chains, so the move makes+ // them stale for every resource below the moved one. Relocating them here+ // keeps the shared registry able to answer the NEXT question — "is the+ // moved resource's new parent an ancestor of the open resource?" — which+ // neither the registry's old crumbs nor the children cache can answer+ // after the chain changed.+ publishGfsMoveRelocation(queryClient, scope, receipt.resourceId, receipt.newParentId)+for (const parentId of plan.refetchChildIds) {void queryClient.invalidateQueries({exact: true,diff --git a/desktop-app/ui/src/lib/gfsOpenLocations.ts b/desktop-app/ui/src/lib/gfsOpenLocations.tsindex 7601f4388..ecd39d221 100644--- a/desktop-app/ui/src/lib/gfsOpenLocations.ts+++ b/desktop-app/ui/src/lib/gfsOpenLocations.ts@@ -68,6 +68,85 @@ export function readGfsOpenLocations(return registry ? Object.values(registry) : []}+/**+ * The chain a location's ancestry takes after a move relocated part of it.+ *+ * The chain is nearest first: [parent, grandparent, …]. A move of X under Y+ * leaves everything BELOW X where it was and replaces the segment ABOVE it:+ * X's old ancestors are gone, and Y (plus Y's own observed ancestors) takes+ * their place. The moved resource itself stays in the chain — it is still an+ * ancestor of the open resource.+ *+ * Y's own ancestors are only known when a surface has Y open; when none has,+ * the chain stops at Y. An unproven link is not a claim.+ */+export function relocateObservedChain(+ chain: readonly string[],+ movedResourceId: string,+ newParentId: string | null,+ newParentChain: readonly string[] = []+): string[] {+ const index = chain.indexOf(movedResourceId)+ if (index < 0) return [...chain]+ const below = chain.slice(0, index)+ if (!newParentId) return [...below, movedResourceId]+ const above = newParentChain.filter(+ ancestor =>+ ancestor !== newParentId && ancestor !== movedResourceId && !below.includes(ancestor)+ )+ return [...below, movedResourceId, newParentId, ...above]+}++/**+ * Apply a committed move to every published chain.+ *+ * The published chains are OBSERVED chains, so a move makes them stale for+ * every resource below the moved one. Relocating them keeps the shared+ * registry able to answer "is X an ancestor of the open resource?": a LATER+ * move of the moved resource's NEW parent would otherwise miss the surfaces+ * that have a descendant open — the registry and the children cache both+ * still hold the pre-move chain.+ */+export function relocatePublishedChains(+ locations: GfsOpenLocationRegistry,+ movedResourceId: string,+ newParentId: string | null+): GfsOpenLocationRegistry {+ // The registry is keyed by MOUNT, so the new parent's own chain is found by+ // the resource it has open — not by the key.+ const newParentChain = newParentId+ ? (Object.values(locations).find(location => location.resourceId === newParentId)+ ?.ancestorResourceIds ?? [])+ : []+ const next: GfsOpenLocationRegistry = {}+ for (const [id, location] of Object.entries(locations)) {+ const relocated = relocateObservedChain(+ location.ancestorResourceIds,+ movedResourceId,+ newParentId,+ newParentChain+ )+ const unchanged =+ relocated.length === location.ancestorResourceIds.length &&+ relocated.every((value, index) => value === location.ancestorResourceIds[index])+ next[id] = unchanged ? location : { ...location, ancestorResourceIds: relocated }+ }+ return next+}++/** Publish the relocation of a committed move into the shared registry. */+export function publishGfsMoveRelocation(+ queryClient: QueryClient,+ sessionScope: string,+ movedResourceId: string,+ newParentId: string | null+): void {+ queryClient.setQueryData<GfsOpenLocationRegistry>(+ desktopQueryKeys.gfsOpenLocations(sessionScope),+ previous => relocatePublishedChains(previous ?? {}, movedResourceId, newParentId)+ )+}+/*** The open resources whose inherited access depends on the moved resource's* ancestry: the resource itself, or any resource below it.