Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
revert: drop prettier-only changes (73 files) to reduce PR review noise
Miguelon Peluchon7ca3ff8bc5ff
diff --git a/control-api/src/gfs/legacyStandaloneGrantMigration.ts b/control-api/src/gfs/legacyStandaloneGrantMigration.tsindex 5f423ac27..05e3fcd4c 100644--- a/control-api/src/gfs/legacyStandaloneGrantMigration.ts+++ b/control-api/src/gfs/legacyStandaloneGrantMigration.ts@@ -86,10 +86,7 @@ function canonicalJson(value: unknown): string {if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`if (value && typeof value === 'object') {const record = value as Record<string, unknown>- return `{${Object.keys(record)- .sort()- .map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)- .join(',')}}`+ return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`}return JSON.stringify(value)}@@ -113,14 +110,12 @@ export async function buildLegacyGrantMigrationReport(api: LegacyGrantMigrationAthrow new Error('migration_inventory_limit_exceeded')}- const sourceGrants = legacy.grants- .map(normalizeGrant)- .sort(- (a, b) =>- a.drive.localeCompare(b.drive) ||- a.resourceId.localeCompare(b.resourceId) ||- a.id.localeCompare(b.id)- )+ const sourceGrants = legacy.grants.map(normalizeGrant).sort(+ (a, b) =>+ a.drive.localeCompare(b.drive) ||+ a.resourceId.localeCompare(b.resourceId) ||+ a.id.localeCompare(b.id)+ )const validIndividualHostCandidates = directory.agents.map(normalizeCandidate).filter((candidate): candidate is TrustedHostCandidate => candidate !== null)@@ -156,9 +151,7 @@ export function validateReviewedLegacyGrantMapping(if (!sameReviewedInventory(mapping.reviewedSourceGrants, report.sourceGrants)) {throw new Error('source_inventory_changed')}- if (- !sameReviewedInventory(mapping.reviewedHostCandidates, report.validIndividualHostCandidates)- ) {+ if (!sameReviewedInventory(mapping.reviewedHostCandidates, report.validIndividualHostCandidates)) {throw new Error('trusted_host_directory_changed')}const grants = new Set(report.sourceGrants.map(grant => grant.id))diff --git a/control-api/src/gfs/seedResources.ts b/control-api/src/gfs/seedResources.tsindex 9458a5282..3ce31a88c 100644--- a/control-api/src/gfs/seedResources.ts+++ b/control-api/src/gfs/seedResources.ts@@ -127,9 +127,10 @@ export class DbSeedResourceStore implements SeedResourceStore {constructor(private readonly db: SeedDb) {}async acquireStructureLock(drive: string): Promise<void> {- await this.db.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [- drive,- ])+ await this.db.query(+ `SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`,+ [drive]+ )}async ensureDirectory(input: {@@ -266,9 +267,7 @@ function directoryRowOf(row: unknown): DirectoryChainRow {function canonicalDirectoryPath(rows: DirectoryChainRow[], drive: string): string {if (rows.length === 0 ||- rows.some(- row => row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory'- ) ||+ rows.some(row => row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory') ||rows.at(-1)?.parent_resource_id !== null ||rows.at(-1)?.name !== GFS_ROOT_NAME) {diff --git a/control-api/src/routes/admin/hostsOverview.ts b/control-api/src/routes/admin/hostsOverview.tsindex efa531bd0..cbf9f0990 100644--- a/control-api/src/routes/admin/hostsOverview.ts+++ b/control-api/src/routes/admin/hostsOverview.ts@@ -3,13 +3,13 @@ import { config } from '../../config.js'import { asyncHandler } from '../../http/asyncHandler.js'import { enforceNamespace } from '../../http/namespaceAudit.js'import { K8sGateway } from '../../k8s.js'-import { buildAgentDirectoryEntry } from '../../services/directory/accessReconciliation.js'import {listAllTeams,listTeamsByAgent,listUsers,listUsersByAgent,} from '../../services/directory/index.js'+import { buildAgentDirectoryEntry } from '../../services/directory/accessReconciliation.js'import { listHostSecrets } from './hostSecrets.js'export function createAdminHostsOverviewRouter(gateway: K8sGateway): Router {diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.tsindex d3a655351..1ba8cccde 100644--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@ -7,8 +7,8 @@ import {} from '../../auth/gfsToken.js'import { config } from '../../config.js'import { pool } from '../../db.js'-import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'+import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'import { asyncHandler } from '../../http/asyncHandler.js'import {type ExternalAuthedRequest,diff --git a/control-api/src/routes/gfs/index.ts b/control-api/src/routes/gfs/index.tsindex b82c8b199..bf88da8d7 100644--- a/control-api/src/routes/gfs/index.ts+++ b/control-api/src/routes/gfs/index.ts@@ -1,6 +1,5 @@import { Router } from 'express'import { registerGfsGrantRoutes } from './grants.js'-import { registerLegacyStandaloneGrantReportRoute } from './legacyStandaloneGrants.js'import { registerGfsProvisionerTokenRoute } from './provisionerToken.js'import { registerGfsProxyRoute } from './proxy.js'import { registerGfsResolveRoutes } from './resolve.js'@@ -9,6 +8,7 @@ import { registerGfsSeedRoute } from './seed.js'import { registerGfsShareRoutes } from './shares.js'import { registerGfsTokenRoute } from './token.js'import { registerGfsTreeRoutes } from './tree.js'+import { registerLegacyStandaloneGrantReportRoute } from './legacyStandaloneGrants.js'/*** gfs (Global File System) router — mounted under /api/v1 BEFORE the internaldiff --git a/control-api/src/routes/gfs/resources.ts b/control-api/src/routes/gfs/resources.tsindex 012ad7fa4..5c2ee7ae9 100644--- a/control-api/src/routes/gfs/resources.ts+++ b/control-api/src/routes/gfs/resources.ts@@ -59,11 +59,7 @@ interface ResourceRow {deleted_at: string | null}-export interface ResourcePatch {- newName?: unknown- newParentId?: unknown- ifMatch?: unknown-}+export interface ResourcePatch { newName?: unknown; newParentId?: unknown; ifMatch?: unknown }async function loadResource(db: GrantsDb, resourceId: string): Promise<ResourceRow | null> {const res = await db.query(@@ -74,9 +70,7 @@ async function loadResource(db: GrantsDb, resourceId: string): Promise<ResourceRreturn (res.rows[0] as ResourceRow | undefined) ?? null}-interface AncestorRow extends ResourceRow {- cycle: boolean-}+interface AncestorRow extends ResourceRow { cycle: boolean }async function acquireStructureLock(db: GrantsDb, drive: string): Promise<void> {await db.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [drive])}@@ -116,8 +110,8 @@ async function loadAncestorChain(db: GrantsDb, resourceId: string): Promise<Ancefunction assertLiveDirectoryChain(rows: AncestorRow[], drive: string): void {if (rows.length === 0 ||- rows.some(- row => row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory'+ rows.some(row =>+ row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory') ||rows.at(-1)?.parent_resource_id !== null) {@@ -126,14 +120,10 @@ function assertLiveDirectoryChain(rows: AncestorRow[], drive: string): void {}function directoryPath(rows: AncestorRow[]): string {- const names = rows- .slice(0, -1)- .map(row => row.name)- .reverse()+ const names = rows.slice(0, -1).map(row => row.name).reverse()return names.length === 0 ? '/' : `/${names.join('/')}`}-const sameChain = (a: AncestorRow[], b: AncestorRow[]) =>- a.length === b.length && a.every((row, i) => row.resource_id === b[i]?.resource_id)+const sameChain = (a: AncestorRow[], b: AncestorRow[]) => a.length === b.length && a.every((row, i) => row.resource_id === b[i]?.resource_id)async function refreshSubtreePaths(db: GrantsDb,drive: string,@@ -214,20 +204,11 @@ export async function applyResourcePatch(if (wantsMove && !UUID_RE.test(requestedDestination!))throw new ResourcePatchError(400, 'path_invalid')- const observedDestination = requestedDestination- ? await loadResource(db, requestedDestination)- : null+ const observedDestination = requestedDestination ? await loadResource(db, requestedDestination) : nullif (requestedDestination && (!observedDestination || observedDestination.deleted_at !== null))throw new ResourcePatchError(404, 'not_found')if (requestedDestination && observedDestination?.drive !== drive) {- await audit({- actorKey: caller.actorKey,- targetKey: caller.actorKey,- op,- drive,- resourceId,- outcome: 'denied',- })+ await audit({ actorKey: caller.actorKey, targetKey: caller.actorKey, op, drive, resourceId, outcome: 'denied' })throw new ResourcePatchError(403, 'cross_boundary')}if (requestedDestination && observedDestination?.kind !== 'directory')@@ -261,8 +242,7 @@ export async function applyResourcePatch(const sourceChain = await loadAncestorChain(db, resource.parent_resource_id)assertLiveDirectoryChain(sourceChain, drive)- if (!sameChain(sourceChain, initialChains[0]))- throw new ResourcePatchError(412, 'precondition_failed')+ if (!sameChain(sourceChain, initialChains[0])) throw new ResourcePatchError(412, 'precondition_failed')const name = wantsRename ? requestedName : resource.namelet newParentId: string | null = resource.parent_resource_idlet parentChain = sourceChain@@ -272,14 +252,7 @@ export async function applyResourcePatch(rid: string): Promise<void> => {if (!(await checkAccess(db, caller, drive, rid, bit))) {- await audit({- actorKey: caller.actorKey,- targetKey: caller.actorKey,- op,- drive,- resourceId,- outcome: 'denied',- })+ await audit({ actorKey: caller.actorKey, targetKey: caller.actorKey, op, drive, resourceId, outcome: 'denied' })throw new ResourcePatchError(403, 'forbidden')}}@@ -299,12 +272,10 @@ export async function applyResourcePatch(destRow.kind !== observedDest.kind ||destRow.parent_resource_id !== observedDest.parent_resource_id ||destRow.version !== observedDest.version- )- throw new ResourcePatchError(412, 'precondition_failed')+ ) throw new ResourcePatchError(412, 'precondition_failed')const destinationChain = await loadAncestorChain(db, dest)assertLiveDirectoryChain(destinationChain, drive)- if (!sameChain(destinationChain, initialChains[1]))- throw new ResourcePatchError(412, 'precondition_failed')+ if (!sameChain(destinationChain, initialChains[1])) throw new ResourcePatchError(412, 'precondition_failed')if (dest === resourceId || destinationChain.some(row => row.resource_id === resourceId)) {throw new ResourcePatchError(400, 'path_invalid')}@@ -335,14 +306,7 @@ export async function applyResourcePatch(const parentPath = directoryPath(parentChain)const rootPath = parentPath === '/' ? `/${name}` : `${parentPath}/${name}`await refreshSubtreePaths(db, drive, resourceId, rootPath)- await audit({- actorKey: caller.actorKey,- targetKey: caller.actorKey,- op,- drive,- resourceId,- outcome: 'allowed',- })+ await audit({ actorKey: caller.actorKey, targetKey: caller.actorKey, op, drive, resourceId, outcome: 'allowed' })return { version }}@@ -355,9 +319,7 @@ export async function handlePatch(req: Request, res: Response): Promise<void> {const caller = resolveCaller(req)const id = String(req.params.id)if (!UUID_RE.test(id)) {- res- .status(400)- .json({ ok: false, error: { code: 'path_invalid', message: 'invalid resource id' } })+ res.status(400).json({ ok: false, error: { code: 'path_invalid', message: 'invalid resource id' } })return}const body = (req.body ?? {}) as ResourcePatchdiff --git a/control-api/src/routes/gfs/seed.ts b/control-api/src/routes/gfs/seed.tsindex 8ee6d00c2..9479a1ed3 100644--- a/control-api/src/routes/gfs/seed.ts+++ b/control-api/src/routes/gfs/seed.ts@@ -50,5 +50,9 @@ export async function handleSeed(req: Request, res: Response): Promise<void> {}export function registerGfsSeedRoute(router: Router): void {- router.post('/gfs/seed', requireInternalControlJwt, asyncHandler(handleSeed))+ router.post(+ '/gfs/seed',+ requireInternalControlJwt,+ asyncHandler(handleSeed)+ )}diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.tsindex 53e36db5b..b8dc38219 100644--- a/control-api/src/services/access/mcpInvocable.ts+++ b/control-api/src/services/access/mcpInvocable.ts@@ -19,8 +19,8 @@*/import type { K8sGateway } from '../../k8s.js'import {- type AgentDirectoryEntry,buildAgentDirectoryEntry,+ type AgentDirectoryEntry,} from '../directory/accessReconciliation.js'export interface InvocableMcpServer {@@ -225,7 +225,11 @@ export async function resolveMcpServersForAgents(const resolvedHosts = await Promise.all(agentNames.map(async requestedName => {try {- const host = (await gateway.getResource('hosts', requestedName, hostsNamespace)) as HostCR+ const host = (await gateway.getResource(+ 'hosts',+ requestedName,+ hostsNamespace+ )) as HostCRconst directoryEntry = buildAgentDirectoryEntry(host, hostsNamespace)if (!directoryEntry || directoryEntry.name !== requestedName) return nullreturn { host, directoryEntry }@@ -241,7 +245,9 @@ export async function resolveMcpServersForAgents(let serverList: McpServerCR[] = []try {- serverList = asArray<McpServerCR>(await gateway.listResource('mcpservers', mcpServersNamespace))+ serverList = asArray<McpServerCR>(+ await gateway.listResource('mcpservers', mcpServersNamespace)+ )} catch (err) {// Directory identity remains useful when optional MCP catalog enrichment// is temporarily unavailable — but the degradation must be observable, ordiff --git a/control-api/src/services/directory/accessReconciliation.ts b/control-api/src/services/directory/accessReconciliation.tsindex e019fbeb1..60b77d793 100644--- a/control-api/src/services/directory/accessReconciliation.ts+++ b/control-api/src/services/directory/accessReconciliation.ts@@ -46,8 +46,10 @@ export function buildAgentDirectoryEntry(const name = typeof host.metadata?.name === 'string' ? host.metadata.name : ''const reportedNamespace = host.metadata?.namespace- if (!name || (trustedNamespace === 'mcp-host' && name === LEGACY_FLEET_WIDE_HOST_SENTINEL))- return null+ if (+ !name ||+ (trustedNamespace === 'mcp-host' && name === LEGACY_FLEET_WIDE_HOST_SENTINEL)+ ) return nullif (reportedNamespace !== trustedNamespace) return nullif (host.metadata?.deletionTimestamp) return nullif (host.spec?.enabled === false) return null@@ -55,7 +57,8 @@ export function buildAgentDirectoryEntry(const subjectId = makeHostSubjectId('1st', trustedNamespace, name)if (!subjectId) return null- const configuredDisplayName = typeof host.spec?.host === 'string' ? host.spec.host.trim() : ''+ const configuredDisplayName =+ typeof host.spec?.host === 'string' ? host.spec.host.trim() : ''return {name,namespace: trustedNamespace,diff --git a/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts b/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.tsindex edf8e6da5..eeae409c4 100644--- a/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts+++ b/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'describe('0073_gfs_audit_decision_evidence', () => {it('adds constrained decision evidence without rewriting existing audit rows', () => {diff --git a/control-api/test/db.gfsBlobGenerationMigration.test.ts b/control-api/test/db.gfsBlobGenerationMigration.test.tsindex 03aac15e3..1c6619078 100644--- a/control-api/test/db.gfsBlobGenerationMigration.test.ts+++ b/control-api/test/db.gfsBlobGenerationMigration.test.ts@@ -1,12 +1,12 @@-import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'describe('0071_gfs_immutable_blob_generations', () => {it('is one additive migration with generation pointers, cleanup state, and path invalidation', () => {const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')expect(source.match(/version: '0071_gfs_immutable_blob_generations'/g)).toHaveLength(1)const start = source.indexOf("version: '0071_gfs_immutable_blob_generations'")- const sql = source.slice(start, source.indexOf('\n },\n]', start))+ const sql = source.slice(start, source.indexOf("\n },\n]", start))expect(sql).toContain('ADD COLUMN IF NOT EXISTS blob_key TEXT NULL')expect(sql).toContain('ADD COLUMN IF NOT EXISTS content_sha256 TEXT NULL')diff --git a/control-api/test/db.gfsReaderRoleMigration.test.ts b/control-api/test/db.gfsReaderRoleMigration.test.tsindex 1ec5c2b7a..ba420391b 100644--- a/control-api/test/db.gfsReaderRoleMigration.test.ts+++ b/control-api/test/db.gfsReaderRoleMigration.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'describe('0072_gfs_reader_database_role', () => {it('adds a NOLOGIN least-privilege reader after immutable blob generations', () => {@@ -18,7 +18,7 @@ describe('0072_gfs_reader_database_role', () => {'NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS')expect(sql).toContain("WHERE member_role.rolname = 'gfs_controller_reader'")- expect(sql).toContain('REVOKE %I FROM gfs_controller_reader')+ expect(sql).toContain("REVOKE %I FROM gfs_controller_reader")expect(sql).toContain('GRANT SELECT ON gfs_resources, gfs_grants, gfs_shares TO gfs_controller_reader')diff --git a/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts b/control-api/test/db.gfsRuntimeRoleContractMigration.test.tsindex ca8590d44..6d114ca47 100644--- a/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts+++ b/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'describe('0074_gfs_runtime_role_exact_contract', () => {it('normalizes both roles without changing credential state', () => {diff --git a/control-api/test/deploy.gfsProvisioning.test.ts b/control-api/test/deploy.gfsProvisioning.test.tsindex 587291b33..ad629cbd9 100644--- a/control-api/test/deploy.gfsProvisioning.test.ts+++ b/control-api/test/deploy.gfsProvisioning.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { spawnSync } from 'node:child_process'import { readFileSync } from 'node:fs'+import { spawnSync } from 'node:child_process'import { fileURLToPath } from 'node:url'function read(relativeFromRepoRoot: string): string {@@ -14,9 +14,7 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {const transitions = read('../../deploy/scripts/lib/gfs-credential-secret.sh')const rollout = read('../../deploy/scripts/lib/gfs-credential-rollout.sh')const recovery = read('../../deploy/scripts/lib/gfs-credential-recovery.sh')- const probePath = fileURLToPath(- new URL('../../deploy/scripts/lib/gfs-dsn-probe.sh', import.meta.url)- )+ const probePath = fileURLToPath(new URL('../../deploy/scripts/lib/gfs-dsn-probe.sh', import.meta.url))const role = 'gfs_controller'const host = 'control-postgres.control-plane.svc.cluster.local'const password = 'a'.repeat(48)@@ -30,73 +28,40 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {})it('keeps reader and writer rotations independent', () => {- const reader = script.slice(- script.lastIndexOf('rotate-reader)'),- script.lastIndexOf('rotate-writer)')- )+ const reader = script.slice(script.lastIndexOf('rotate-reader)'), script.lastIndexOf('rotate-writer)'))const writer = script.slice(script.lastIndexOf('rotate-writer)'))- expect(reader).toContain(- 'reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader true'- )+ expect(reader).toContain('reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader true')expect(reader).not.toContain('gfsc-writer')- expect(writer).toContain(- 'reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true'- )+ expect(writer).toContain('reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true')expect(writer).not.toContain('gfsc-reader')- const reconciliation = script.slice(- script.indexOf('reconcile_credential()'),- script.lastIndexOf('case "$MODE"')- )- expect(reconciliation.indexOf('ensure_pending_candidate')).toBeLessThan(- reconciliation.indexOf('set_role_password')- )- expect(reconciliation.indexOf('claim_secret_candidate')).toBeLessThan(- reconciliation.indexOf('set_role_password')- )- expect(reconciliation.indexOf('set_role_password')).toBeLessThan(- reconciliation.indexOf('promote_candidate')- )- expect(reconciliation.indexOf('promote_candidate')).toBeLessThan(- reconciliation.lastIndexOf('complete_rollout')- )+ const reconciliation = script.slice(script.indexOf('reconcile_credential()'), script.lastIndexOf('case "$MODE"'))+ expect(reconciliation.indexOf('ensure_pending_candidate')).toBeLessThan(reconciliation.indexOf('set_role_password'))+ expect(reconciliation.indexOf('claim_secret_candidate')).toBeLessThan(reconciliation.indexOf('set_role_password'))+ expect(reconciliation.indexOf('set_role_password')).toBeLessThan(reconciliation.indexOf('promote_candidate'))+ expect(reconciliation.indexOf('promote_candidate')).toBeLessThan(reconciliation.lastIndexOf('complete_rollout'))})it('adopts legacy writer state without rotating or restarting it', () => {- const adoption = script.slice(- script.indexOf('stage_writer()'),- script.lastIndexOf('case "$MODE"')- )+ const adoption = script.slice(script.indexOf('stage_writer()'), script.lastIndexOf('case "$MODE"'))expect(adoption).toContain('load_secret_snapshot "$WRITER_SECRET"')expect(adoption).toContain('dsn_has_role "$GFS_SNAPSHOT_ACTIVE" gfs_controller')- expect(adoption).toContain(- 'authenticate_or_restore_nologin gfs_controller writer "$GFS_SNAPSHOT_ACTIVE"'- )+ expect(adoption).toContain('authenticate_or_restore_nologin gfs_controller writer "$GFS_SNAPSHOT_ACTIVE"')expect(adoption).toContain('verify_role_contract gfs_controller writer')expect(adoption).toContain('credential_adoption_timestamp gfsc-writer')- expect(adoption).toContain(- 'adopt_legacy_secret_state "$WRITER_SECRET" "$GFS_SNAPSHOT_RV" "$GFS_SNAPSHOT_ANNOTATIONS"'- )+ expect(adoption).toContain('adopt_legacy_secret_state "$WRITER_SECRET" "$GFS_SNAPSHOT_RV" "$GFS_SNAPSHOT_ANNOTATIONS"')expect(adoption).toContain('[ "$(secret_dsn "$WRITER_SECRET")" = "$GFS_SNAPSHOT_ACTIVE" ]')expect(adoption).not.toContain('set_role_password')expect(adoption).not.toContain('complete_rollout')- expect(transitions).toContain(- '{"op": "test", "path": "/metadata/resourceVersion", "value": rv}'- )+ expect(transitions).toContain('{"op": "test", "path": "/metadata/resourceVersion", "value": rv}')expect(transitions).toContain('get secret "$secret" -o json')expect(transitions).toContain('GFS_SNAPSHOT_ROTATED_AT=')expect(rollout).toContain('input === process.env.GFS_PG_CONNECTION_STRING')})it('checks table, sequence, and membership boundaries explicitly', () => {- expect(script).toContain(- "has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'USAGE')"- )- expect(script).toContain(- "has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'SELECT')"- )- expect(script).toContain(- "NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')"- )+ expect(script).toContain("has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'USAGE')")+ expect(script).toContain("has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'SELECT')")+ expect(script).toContain("NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')")expect(script).toContain('NOT rolinherit')expect(script).toContain('pg_auth_members')expect(script).toContain("has_table_privilege(:'role_name', 'gfs_resources', 'INSERT')")@@ -120,30 +85,18 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {})it('probes preserved reader authentication without exposing connection material', () => {- const stage = script.slice(- script.lastIndexOf('stage-reader)'),- script.lastIndexOf('rotate-reader)')- )- expect(stage).toContain(- 'reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader false'- )+ const stage = script.slice(script.lastIndexOf('stage-reader)'), script.lastIndexOf('rotate-reader)'))+ expect(stage).toContain('reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader false')expect(script).toContain('gfs_dsn_authenticates_as "$1" "$2"')expect(probe).toContain('kc -n "$PG_NS" exec -i "$PG_PROBE_DEPLOY" -- node -e')expect(probe).toContain('await client.query("SELECT current_user")')expect(probe).toContain('[ "$actual" = "$expected_role" ]')expect(probe).toContain('error.code === "28P01" || error.code === "28000"')expect(probe).toContain('[ "$rc" -eq 41 ] && [ "$actual" = GFS_DSN_AUTH_REJECTED ]')- const roleCheck = script.slice(- script.indexOf('verify_role()'),- script.indexOf('set_role_password()')- )+ const roleCheck = script.slice(script.indexOf('verify_role()'), script.indexOf('set_role_password()'))expect(roleCheck).toContain('persisted="$(secret_dsn "${!ref_name}")"')- expect(roleCheck.indexOf('dsn_has_role "$persisted"')).toBeLessThan(- roleCheck.indexOf('require_authenticated_dsn "$persisted"')- )- expect(roleCheck.indexOf('require_authenticated_dsn "$persisted"')).toBeLessThan(- roleCheck.indexOf('verify_role_contract "$role" "$kind"')- )+ expect(roleCheck.indexOf('dsn_has_role "$persisted"')).toBeLessThan(roleCheck.indexOf('require_authenticated_dsn "$persisted"'))+ expect(roleCheck.indexOf('require_authenticated_dsn "$persisted"')).toBeLessThan(roleCheck.indexOf('verify_role_contract "$role" "$kind"'))expect(recovery).toContain('die "$3 authentication probe unavailable"')expect(recovery).toContain('authentication probe unavailable; refusing credential mutation')expect(recovery).toContain('disable_role_login "$role"')@@ -179,9 +132,7 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {expect(transitions).toContain('{"op": "test", "path": state_path, "value": "pending"}')expect(transitions).toContain('{"op": "replace", "path": state_path, "value": "applying"}')expect(transitions).toContain('{"op": "test", "path": state_path, "value": "applying"}')- expect(transitions).toContain(- '{"op": "replace", "path": state_path, "value": "rollout-pending"}'- )+ expect(transitions).toContain('{"op": "replace", "path": state_path, "value": "rollout-pending"}')expect(transitions).toContain('{"op": "test", "path": pending_path, "value": candidate}')expect(rollout).toContain('rollout-running')expect(script).not.toContain('\\quit 1')@@ -189,19 +140,11 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {})it('accepts only the exact persisted endpoint and rejects URI overrides', () => {- const run = (input: string) =>- spawnSync(- 'bash',- [- '-c',- 'source "$1"; gfs_dsn_validate "$2" "$3" 5432 profiles',- 'bash',- probePath,- role,- host,- ],- { input, encoding: 'utf8' }- )+ const run = (input: string) => spawnSync(+ 'bash',+ ['-c', 'source "$1"; gfs_dsn_validate "$2" "$3" 5432 profiles', 'bash', probePath, role, host],+ { input, encoding: 'utf8' }+ )const accepted = run(uri(`@${host}:5432/profiles`))expect(accepted.status).toBe(0)expect(accepted.stdout).toBe('')diff --git a/control-api/test/gfs.seedResources.test.ts b/control-api/test/gfs.seedResources.test.tsindex 6f31d07d5..45bf57b17 100644--- a/control-api/test/gfs.seedResources.test.ts+++ b/control-api/test/gfs.seedResources.test.ts@@ -189,13 +189,7 @@ describe('DbSeedResourceStore.ensureDirectory (idempotent upsert)', () => {it('fails loud if neither insert nor select yields a row (no silent empty id)', async () => {const db = new FakeDb()- db.responses = [- { rows: [root] },- { rows: [root] },- { rows: [root] },- { rows: [] },- { rows: [] },- ]+ db.responses = [{ rows: [root] }, { rows: [root] }, { rows: [root] }, { rows: [] }, { rows: [] }]await expect(new DbSeedResourceStore(db).ensureDirectory({drive: 'main',diff --git a/control-api/test/gfs.seedRouteTransaction.test.ts b/control-api/test/gfs.seedRouteTransaction.test.tsindex 7fa87145e..759f03668 100644--- a/control-api/test/gfs.seedRouteTransaction.test.ts+++ b/control-api/test/gfs.seedRouteTransaction.test.ts@@ -1,5 +1,4 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { handleSeed } from '../src/routes/gfs/seed.js'const state = vi.hoisted(() => {const events: string[] = []@@ -42,6 +41,8 @@ vi.mock('../src/middleware/internalControlJwt.js', () => ({requireInternalControlJwt: (_req: unknown, _res: unknown, next: () => void) => next(),}))+import { handleSeed } from '../src/routes/gfs/seed.js'+function response() {return {code: 0,diff --git a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.tsindex 8ed4db116..0e5168b45 100644--- a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts+++ b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts@@ -1,5 +1,5 @@-import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { randomBytes } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { Pool, type PoolClient } from 'pg'import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'@@ -74,15 +74,13 @@ describeRealPostgres('GFS typed audit decision evidence', () => {AND table_name = 'gfs_audit'AND column_name = ANY($1::text[])ORDER BY column_name`,- [- [- 'record_type',- 'matched_subject',- 'authorization_source',- 'cached_authorization_source',- 'mutation_outcome',- ],- ]+ [[+ 'record_type',+ 'matched_subject',+ 'authorization_source',+ 'cached_authorization_source',+ 'mutation_outcome',+ ]])expect(columns.rows).toHaveLength(5)expect(columns.rows.find(row => row.column_name === 'record_type')).toMatchObject({diff --git a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts b/control-api/test/gfsBlobMigration.realPostgres.integration.test.tsindex 20eea0d10..1d9bea0e4 100644--- a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts+++ b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts@@ -1,5 +1,5 @@-import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { randomBytes, randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { Pool } from 'pg'import { initDb } from '../src/db.js'@@ -59,15 +59,8 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {ORDER BY ordinal_position`)expect(columns.rows.map(row => row.column_name)).toEqual([- 'blob_key',- 'request_id',- 'resource_id',- 'candidate_kind',- 'content_sha256',- 'bytes',- 'state',- 'created_at',- 'updated_at',+ 'blob_key', 'request_id', 'resource_id', 'candidate_kind', 'content_sha256',+ 'bytes', 'state', 'created_at', 'updated_at',])expect(columns.rows.find(row => row.column_name === 'content_sha256')?.is_nullable).toBe('YES')@@ -78,8 +71,7 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {ORDER BY conname`)expect(constraints.rows.map(row => row.conname)).toEqual([- 'gfs_blob_manifests_blob_key_valid',- 'gfs_resources_blob_metadata_pair',+ 'gfs_blob_manifests_blob_key_valid', 'gfs_resources_blob_metadata_pair',])expect(constraints.rows.map(row => row.definition).join(' ')).toMatch(/generation.*legacy_flat.*content_sha256 IS NULL/s@@ -91,8 +83,7 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {ORDER BY indexname`)expect(indexes.rows.map(row => row.indexname)).toEqual([- 'gfs_blob_manifests_cleanup_idx',- 'gfs_resources_blob_key_uniq',+ 'gfs_blob_manifests_cleanup_idx', 'gfs_resources_blob_key_uniq',])expect(indexes.rows[0]?.indexdef).toContain('(state, updated_at, blob_key)')expect(indexes.rows[1]?.indexdef).toContain('WHERE (blob_key IS NOT NULL)')@@ -107,14 +98,8 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {has_table_privilege('gfs_controller','gfs_blob_manifests','UPDATE') AS manifest_update,has_table_privilege('gfs_controller','gfs_blob_manifests','DELETE') AS manifest_delete`)expect(acl.rows[0]).toEqual({- resource_read: true,- resource_insert: true,- resource_update: true,- resource_delete: false,- manifest_read: true,- manifest_insert: true,- manifest_update: true,- manifest_delete: true,+ resource_read: true, resource_insert: true, resource_update: true, resource_delete: false,+ manifest_read: true, manifest_insert: true, manifest_update: true, manifest_delete: true,})})@@ -133,13 +118,10 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {`UPDATE gfs_resources SET blob_key=$2,content_sha256=$3 WHERE resource_id=$1`,[resourceId, generationKey, 'a'.repeat(64)])- await expect(- pool.query(`UPDATE gfs_resources SET blob_key=$2,content_sha256=$3 WHERE resource_id=$1`, [- resourceId,- `${rootId.replaceAll('-', '')}/${randomUUID()}`,- 'a'.repeat(64),- ])- ).rejects.toMatchObject({ code: '23514' })+ await expect(pool.query(+ `UPDATE gfs_resources SET blob_key=$2,content_sha256=$3 WHERE resource_id=$1`,+ [resourceId, `${rootId.replaceAll('-', '')}/${randomUUID()}`, 'a'.repeat(64)]+ )).rejects.toMatchObject({ code: '23514' })await pool.query(`INSERT INTO gfs_blob_manifests(blob_key,request_id,resource_id,candidate_kind,content_sha256,bytes,state)@@ -147,13 +129,11 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {($5,$6,$3,'legacy_flat',NULL,1,'deleting')`,[generationKey, randomUUID(), resourceId, 'a'.repeat(64), compactId, randomUUID()])- await expect(- pool.query(- `INSERT INTO gfs_blob_manifests+ await expect(pool.query(+ `INSERT INTO gfs_blob_manifests(blob_key,request_id,resource_id,candidate_kind,content_sha256,bytes,state)VALUES ($1,$2,$3,'legacy_flat',$4,1,'deleting')`,- [rootId.replaceAll('-', ''), randomUUID(), rootId, 'b'.repeat(64)]- )- ).rejects.toMatchObject({ code: '23514' })+ [rootId.replaceAll('-', ''), randomUUID(), rootId, 'b'.repeat(64)]+ )).rejects.toMatchObject({ code: '23514' })})})diff --git a/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts b/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.tsindex 9b66ae892..5007419cf 100644--- a/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts+++ b/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts@@ -1,16 +1,16 @@-import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'import { randomBytes, randomUUID } from 'node:crypto'import { existsSync } from 'node:fs'import { mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { Pool } from 'pg'-import { reconcileExpiredBlobs } from '../../gfs-controller/src/db/blobReconciliation.js'+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'+import { initDb } from '../src/db.js'import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'-import type { GfsMetrics } from '../../gfs-controller/src/metrics.js'+import { reconcileExpiredBlobs } from '../../gfs-controller/src/db/blobReconciliation.js'import { BlobStore } from '../../gfs-controller/src/storage/blobStore.js'import { resolveBlobKeyPath, resolveBlobPath } from '../../gfs-controller/src/storage/paths.js'-import { initDb } from '../src/db.js'+import type { GfsMetrics } from '../../gfs-controller/src/metrics.js'// This suite closes the reconciler's HIGH coverage gap: reconcileExpiredBlobs is// the sole backstop for the write/copy paths' swallowed cleanup errors, yet its@@ -52,10 +52,7 @@ function metricsStub(): { metrics: GfsMetrics; failures: number } {describeRealPostgres('GFS blob reconciliation on real PostgreSQL + on-disk BlobStore', () => {const database = `gfs_recon_${randomBytes(6).toString('hex')}`- const connectionString = databaseUrl(- adminUrl ?? 'postgresql://[email protected]/postgres',- database- )+ const connectionString = databaseUrl(adminUrl ?? 'postgresql://[email protected]/postgres', database)let adminPool: Poollet pool: Poollet blobRoot: string@@ -77,9 +74,7 @@ describeRealPostgres('GFS blob reconciliation on real PostgreSQL + on-disk BlobS}async function manifestState(blobKey: string): Promise<string | null> {- const res = await pool.query('SELECT state FROM gfs_blob_manifests WHERE blob_key = $1', [- blobKey,- ])+ const res = await pool.query('SELECT state FROM gfs_blob_manifests WHERE blob_key = $1', [blobKey])return res.rows[0]?.state ?? null}diff --git a/control-api/test/gfsCopy.realPostgres.integration.test.ts b/control-api/test/gfsCopy.realPostgres.integration.test.tsindex 50a7399a0..710a2463a 100644--- a/control-api/test/gfsCopy.realPostgres.integration.test.ts+++ b/control-api/test/gfsCopy.realPostgres.integration.test.ts@@ -1,16 +1,16 @@-import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { randomBytes, randomUUID } from 'node:crypto'import { mkdtemp, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { Pool } from 'pg'+import { initDb } from '../src/db.js'import { preflightCopy } from '../../gfs-controller/src/api/copy.js'import { DbAuditSink } from '../../gfs-controller/src/authz/audit.js'import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'import { PgResourceStore } from '../../gfs-controller/src/db/resourceStore.js'import { GfsWriteService, PgTransactor } from '../../gfs-controller/src/db/writeStore.js'import { BlobStore } from '../../gfs-controller/src/storage/blobStore.js'-import { initDb } from '../src/db.js'const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -74,16 +74,8 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem blo['second', Buffer.from(`second-${label}-payload`)],]),}- const firstBlob = await blobs.writeImmutable(- tree.firstFileId,- randomUUID(),- tree.files.get('first')!- )- const secondBlob = await blobs.writeImmutable(- tree.secondFileId,- randomUUID(),- tree.files.get('second')!- )+ const firstBlob = await blobs.writeImmutable(tree.firstFileId, randomUUID(), tree.files.get('first')!)+ const secondBlob = await blobs.writeImmutable(tree.secondFileId, randomUUID(), tree.files.get('second')!)await pool.query(`INSERT INTO gfs_resources(resource_id, drive, parent_resource_id, name, kind, path_cache, version,@@ -117,11 +109,7 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem bloasync function planFor(tree: SeededTree, newName?: string) {const snapshot = await resources.loadCopySnapshot(tree.drive, tree.sourceId, 1_001n)const rootName = newName ?? snapshot.find(node => node.depth === 0)!.name- const destination = await resources.loadCopyDestination(- tree.drive,- tree.destinationId,- rootName- )+ const destination = await resources.loadCopyDestination(tree.drive, tree.destinationId, rootName)return {snapshot,destination,@@ -209,22 +197,15 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem blo'/archive/source-copy/nested','/archive/source-copy/nested/second.txt',])- const sourceIds = new Set(- [tree.sourceId, tree.nestedId, tree.firstFileId, tree.secondFileId].map(compact)- )+ const sourceIds = new Set([tree.sourceId, tree.nestedId, tree.firstFileId, tree.secondFileId].map(compact))expect(copied.rows.every(row => !sourceIds.has(compact(String(row.resource_id))))).toBe(true)- expect(- copied.rows- .filter(row => row.kind === 'file')- .map(row => Number(row.bytes))- .sort((a, b) => a - b)- ).toEqual([...tree.files.values()].map(value => value.length).sort((a, b) => a - b))+ expect(copied.rows.filter(row => row.kind === 'file').map(row => Number(row.bytes)).sort((a, b) => a - b)).toEqual(+ [...tree.files.values()].map(value => value.length).sort((a, b) => a - b)+ )const copiedFiles = copied.rows.filter(row => row.kind === 'file')const copiedPayloads = await Promise.all(- copiedFiles.map(async row =>- readAll(await blobs.read(String(row.resource_id), String(row.blob_key)))- )+ copiedFiles.map(async row => readAll(await blobs.read(String(row.resource_id), String(row.blob_key)))))expect(copiedPayloads.map(value => value.toString()).sort()).toEqual([...tree.files.values()].map(value => value.toString()).sort()@@ -252,34 +233,22 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem bloVALUES ($1,$2,$3,'source','directory','/archive/source',0,0)`,[randomUUID(), tree.drive, tree.destinationId])- const before = await pool.query(- `SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`,- [tree.drive]- )+ const before = await pool.query(`SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`, [tree.drive])const snapshot = await resources.loadCopySnapshot(tree.drive, tree.sourceId, 1_001n)- const destination = await resources.loadCopyDestination(- tree.drive,- tree.destinationId,- 'source'- )- expect(() =>- preflightCopy({- drive: tree.drive,- sourceResourceId: tree.sourceId,- destinationParentId: tree.destinationId,- ifMatch: 3,- snapshot,- destination,- maxObjects: 1_000,- maxBytes: 1_073_741_824,- deadlineAtMs: Date.now() + 30_000,- nowMs: Date.now(),- })- ).toThrow(expect.objectContaining({ code: 'already_exists' }))- const after = await pool.query(- `SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`,- [tree.drive]- )+ const destination = await resources.loadCopyDestination(tree.drive, tree.destinationId, 'source')+ expect(() => preflightCopy({+ drive: tree.drive,+ sourceResourceId: tree.sourceId,+ destinationParentId: tree.destinationId,+ ifMatch: 3,+ snapshot,+ destination,+ maxObjects: 1_000,+ maxBytes: 1_073_741_824,+ deadlineAtMs: Date.now() + 30_000,+ nowMs: Date.now(),+ })).toThrow(expect.objectContaining({ code: 'already_exists' }))+ const after = await pool.query(`SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`, [tree.drive])const manifests = await pool.query(`SELECT count(*)::integer AS count FROM gfs_blob_manifests WHERE resource_id IN(SELECT resource_id FROM gfs_resources WHERE drive=$1)`,@@ -293,22 +262,18 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem bloconst tree = await seedTree('version-change')const frozen = await planFor(tree, 'stale-copy')const requestId = randomUUID()- await pool.query('UPDATE gfs_resources SET version=version+1 WHERE resource_id=$1', [- tree.secondFileId,- ])+ await pool.query('UPDATE gfs_resources SET version=version+1 WHERE resource_id=$1', [tree.secondFileId])- await expect(- writes.copy({- requestId,- subject: 'host:sandbox-recipes/copy-real-pg',- audit,- drive: tree.drive,- destinationParentId: tree.destinationId,- plan: frozen.plan,- destination: frozen.destination,- deadlineAtMs: Date.now() + 30_000,- })- ).rejects.toMatchObject({ code: 'precondition_failed' })+ await expect(writes.copy({+ requestId,+ subject: 'host:sandbox-recipes/copy-real-pg',+ audit,+ drive: tree.drive,+ destinationParentId: tree.destinationId,+ plan: frozen.plan,+ destination: frozen.destination,+ deadlineAtMs: Date.now() + 30_000,+ })).rejects.toMatchObject({ code: 'precondition_failed' })const copied = await pool.query(`SELECT count(*)::integer AS count FROM gfs_resources@@ -319,9 +284,10 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem blo`SELECT count(*)::integer AS count FROM gfs_blob_manifests WHERE request_id=$1`,[requestId])- const outcome = await pool.query(`SELECT mutation_outcome FROM gfs_audit WHERE request_id=$1`, [- requestId,- ])+ const outcome = await pool.query(+ `SELECT mutation_outcome FROM gfs_audit WHERE request_id=$1`,+ [requestId]+ )expect(copied.rows[0]?.count).toBe(0)expect(manifests.rows[0]?.count).toBe(0)expect(outcome.rows).toEqual([{ mutation_outcome: 'failed' }])diff --git a/control-api/test/gfsGrants.test.ts b/control-api/test/gfsGrants.test.tsindex 4a8f0bdc1..93781d5fc 100644--- a/control-api/test/gfsGrants.test.ts+++ b/control-api/test/gfsGrants.test.ts@@ -773,15 +773,13 @@ describe('assertMayGrant — agent (host) restrictions', () => {it('preserves the existing folder-owner manager restriction for third-party hosts', async () => {const db = mockDb({ancestors: { [R]: [R] },- grants: [- {- subject_type: 'user',- subject_id: 'owner',- resource_id: R,- permissions: ['read', 'manage_acl'],- inherit: true,- },- ],+ grants: [{+ subject_type: 'user',+ subject_id: 'owner',+ resource_id: R,+ permissions: ['read', 'manage_acl'],+ inherit: true,+ }],})await expect(diff --git a/control-api/test/gfsHostSubject.test.ts b/control-api/test/gfsHostSubject.test.tsindex 3afbcf71b..c73c4206e 100644--- a/control-api/test/gfsHostSubject.test.ts+++ b/control-api/test/gfsHostSubject.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'import { makeHostSubjectId } from '../src/gfs/hostSubject.js'import { parseSubject } from '../src/routes/gfs/grants.js'diff --git a/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts b/control-api/test/gfsLegacyStandaloneGrantMigration.test.tsindex 1cb159132..7595abf12 100644--- a/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts+++ b/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it, vi } from 'vitest'import { readFile } from 'node:fs/promises'+import { describe, expect, it, vi } from 'vitest'import {LEGACY_STANDALONE_SUBJECT_KEY,applyReviewedLegacyGrantMigration,@@ -59,7 +59,8 @@ describe('legacy standalone GFS grant migration', () => {}const registrations = router.stack.filter(layer =>- layer.route?.path === '/gfs/grants/legacy-standalone' && layer.route.methods.get === true+ layer.route?.path === '/gfs/grants/legacy-standalone' &&+ layer.route.methods.get === true)expect(registrations).toHaveLength(1)@@ -85,10 +86,7 @@ describe('legacy standalone GFS grant migration', () => {const report = await buildLegacyGrantMigrationReport(api)expect(report.sourceGrants).toEqual([{ ...SOURCE_GRANT, permissions: ['read', 'write'] }])- expect(report.validIndividualHostCandidates.map(item => item.name)).toEqual([- 'agent-a',- 'agent-b',- ])+ expect(report.validIndividualHostCandidates.map(item => item.name)).toEqual(['agent-a', 'agent-b'])expect(report.mappingTemplate.mappings).toEqual([{ sourceGrantId: SOURCE_ID, targets: [] }])expect(api.putGrant).not.toHaveBeenCalled()})@@ -162,12 +160,10 @@ describe('legacy standalone GFS grant migration', () => {const report = await buildLegacyGrantMigrationReport(api)const duplicate = {...report.mappingTemplate,- mappings: [- {- sourceGrantId: SOURCE_ID,- targets: ['host:1st:mcp-host/agent-a', 'host:1st:mcp-host/agent-a'],- },- ],+ mappings: [{+ sourceGrantId: SOURCE_ID,+ targets: ['host:1st:mcp-host/agent-a', 'host:1st:mcp-host/agent-a'],+ }],}expect(() => validateReviewedLegacyGrantMapping(report, duplicate)).toThrow('mapping_target_duplicate'@@ -178,27 +174,23 @@ describe('legacy standalone GFS grant migration', () => {'team:all-agents','host:1st:mcp-host/all-agents',]) {- expect(() =>- validateReviewedLegacyGrantMapping(report, {- ...report.mappingTemplate,- mappings: [{ sourceGrantId: SOURCE_ID, targets: [target] }],- })- ).toThrow('mapping_target_not_current_trusted_host')+ expect(() => validateReviewedLegacyGrantMapping(report, {+ ...report.mappingTemplate,+ mappings: [{ sourceGrantId: SOURCE_ID, targets: [target] }],+ })).toThrow('mapping_target_not_current_trusted_host')}})it('uses a bounded read-only query for inventory and no direct grant-row SQL in apply', async () => {- const query = vi.fn(async () => ({- rows: [- {- id: SOURCE_ID,- drive: 'main',- resource_id: RESOURCE_ID,- permissions: ['write', 'read'],- inherit: true,- },- ],- }))+ const query = vi.fn(async () => ({ rows: [+ {+ id: SOURCE_ID,+ drive: 'main',+ resource_id: RESOURCE_ID,+ permissions: ['write', 'read'],+ inherit: true,+ },+ ] }))await expect(listLegacyStandaloneGrants({ query })).resolves.toEqual([{ ...SOURCE_GRANT, permissions: ['read', 'write'] },])@@ -206,10 +198,7 @@ describe('legacy standalone GFS grant migration', () => {expect(query.mock.calls[0][0]).toContain('LIMIT $2')expect(query.mock.calls[0][1]).toEqual(['1st:mcp-host/standalone', 1001])- const script = await readFile(- new URL('../../scripts/gfs-legacy-standalone-grants.mjs', import.meta.url),- 'utf8'- )+ const script = await readFile(new URL('../../scripts/gfs-legacy-standalone-grants.mjs', import.meta.url), 'utf8')expect(script).not.toMatch(/INSERT\s+INTO|UPDATE\s+gfs_grants|DELETE\s+FROM/i)expect(script).toContain("'/api/v1/gfs/grants'")})diff --git a/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts b/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.tsindex e234d4568..55a244c1a 100644--- a/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts+++ b/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts@@ -63,8 +63,9 @@ function denied() {}async function buildApp() {- const { registerLegacyStandaloneGrantReportRoute } =- await import('../src/routes/gfs/legacyStandaloneGrants.js')+ const { registerLegacyStandaloneGrantReportRoute } = await import(+ '../src/routes/gfs/legacyStandaloneGrants.js'+ )const router = express.Router()registerLegacyStandaloneGrantReportRoute(router)const app = express()diff --git a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts b/control-api/test/gfsReaderRole.realPostgres.integration.test.tsindex 0844d4a38..245b7c028 100644--- a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts+++ b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts@@ -1,8 +1,8 @@-import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { randomBytes } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { Pool } from 'pg'-import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'+import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -54,9 +54,7 @@ describeRealPostgres('GFS reader and writer login isolation', () => {// authenticate directly with independent secrets. NOINHERIT prevents an// accidental membership from widening either direct-login envelope.await pool.query(`ALTER ROLE gfs_controller LOGIN NOINHERIT PASSWORD '${writerPassword}'`)- await pool.query(- `ALTER ROLE gfs_controller_reader LOGIN NOINHERIT PASSWORD '${readerPassword}'`- )+ await pool.query(`ALTER ROLE gfs_controller_reader LOGIN NOINHERIT PASSWORD '${readerPassword}'`)writerPool = new Pool({ connectionString: writerUrl })readerPool = new Pool({ connectionString: readerUrl })}, 60_000)@@ -172,24 +170,14 @@ describeRealPostgres('GFS reader and writer login isolation', () => {})it('passes reader readiness without any manifest privilege and passes writer readiness with it', async () => {- await expect(readerPool.query('SELECT 1 FROM gfs_blob_manifests')).rejects.toMatchObject({- code: '42501',- })+ await expect(readerPool.query('SELECT 1 FROM gfs_blob_manifests')).rejects.toMatchObject({ code: '42501' })await expect(readiness(readerPool, readerUrl, 'reader')()).resolves.toBeUndefined()await expect(readiness(writerPool, writerUrl, 'writer')()).resolves.toBeUndefined()})it.each([- [- 'SELECT on resources',- 'REVOKE SELECT ON gfs_resources FROM gfs_controller_reader',- 'GRANT SELECT ON gfs_resources TO gfs_controller_reader',- ],- [- 'INSERT on audit',- 'REVOKE INSERT ON gfs_audit FROM gfs_controller_reader',- 'GRANT INSERT ON gfs_audit TO gfs_controller_reader',- ],+ ['SELECT on resources', 'REVOKE SELECT ON gfs_resources FROM gfs_controller_reader', 'GRANT SELECT ON gfs_resources TO gfs_controller_reader'],+ ['INSERT on audit', 'REVOKE INSERT ON gfs_audit FROM gfs_controller_reader', 'GRANT INSERT ON gfs_audit TO gfs_controller_reader'],])('fails reader readiness after revoking %s', async (_label, revokeSql, restoreSql) => {await pool.query(revokeSql)try {@@ -250,18 +238,18 @@ describeRealPostgres('GFS reader and writer login isolation', () => {await expect(runtimePool().query('UPDATE control_admin_users SET status = status WHERE false')).rejects.toMatchObject({ code: '42501' })- await expect(runtimePool().query('DELETE FROM team_members WHERE false')).rejects.toMatchObject(- { code: '42501' }- )+ await expect(+ runtimePool().query('DELETE FROM team_members WHERE false')+ ).rejects.toMatchObject({ code: '42501' })})it('preserves required writer mutation privileges but denies hard deletion', async () => {await expect(writerPool.query('UPDATE gfs_resources SET bytes = bytes WHERE false')).resolves.toMatchObject({ rowCount: 0 })- await expect(writerPool.query('DELETE FROM gfs_resources WHERE false')).rejects.toMatchObject({- code: '42501',- })+ await expect(+ writerPool.query('DELETE FROM gfs_resources WHERE false')+ ).rejects.toMatchObject({ code: '42501' })await expect(writerPool.query('UPDATE gfs_blob_manifests SET updated_at = updated_at WHERE false')).resolves.toMatchObject({ rowCount: 0 })diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.tsindex b12f2eeab..1b676e21e 100644--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts@@ -1,9 +1,9 @@-import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { randomBytes } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { Pool } from 'pg'-import type { PoolClient } from 'pg'-import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'import { assertDbReady, initDb } from '../src/db.js'+import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'+import type { PoolClient } from 'pg'const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skipdiff --git a/control-api/test/gfsResources.routeTransaction.test.ts b/control-api/test/gfsResources.routeTransaction.test.tsindex 5d98181a6..b1f0e63a9 100644--- a/control-api/test/gfsResources.routeTransaction.test.ts+++ b/control-api/test/gfsResources.routeTransaction.test.ts@@ -1,5 +1,4 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { handlePatch } from '../src/routes/gfs/resources.js'const FILE = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'const OTHER = 'dddddddd-dddd-dddd-dddd-dddddddddddd'@@ -65,21 +64,12 @@ const state = vi.hoisted(() => {}if (text.includes('FROM gfs_resources')) {const id = String(values?.[0])- return {- rows: [id === source.resource_id ? source : id === other.resource_id ? other : file],- }+ return { rows: [id === source.resource_id ? source : id === other.resource_id ? other : file] }}return { rows: [] }}),}- return {- events,- db,- failPaths: false,- operator: true,- auditDb: undefined as unknown,- audits: [] as unknown[],- }+ return { events, db, failPaths: false, operator: true, auditDb: undefined as unknown, audits: [] as unknown[] }})vi.mock('../src/db.js', () => ({@@ -117,6 +107,8 @@ vi.mock('../src/routes/gfs/grants.js', () => ({}),}))+import { handlePatch } from '../src/routes/gfs/resources.js'+function response() {return {code: 0,@@ -145,12 +137,7 @@ describe('gfs resource route transaction boundary', () => {it('commits mutation, path refresh, and audit through the same transaction client', async () => {const res = response()await handlePatch(- {- params: { id: FILE },- body: { newName: 'b.md' },- query: { drive: 'main' },- ip: '127.0.0.1',- } as never,+ { params: { id: FILE }, body: { newName: 'b.md' }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,res as never)expect(res.code).toBe(200)@@ -170,12 +157,7 @@ describe('gfs resource route transaction boundary', () => {state.failPaths = trueconst res = response()await handlePatch(- {- params: { id: FILE },- body: { newName: 'b.md' },- query: { drive: 'main' },- ip: '127.0.0.1',- } as never,+ { params: { id: FILE }, body: { newName: 'b.md' }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,res as never)expect(res.code).toBe(412)@@ -188,12 +170,7 @@ describe('gfs resource route transaction boundary', () => {state.operator = falseconst res = response()await handlePatch(- {- params: { id: FILE },- body: { newName: 'b.md' },- query: { drive: 'main' },- ip: '127.0.0.1',- } as never,+ { params: { id: FILE }, body: { newName: 'b.md' }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,res as never)expect(res.code).toBe(403)@@ -205,12 +182,7 @@ describe('gfs resource route transaction boundary', () => {it('commits exactly one cross-boundary denial audit and no mutation', async () => {const res = response()await handlePatch(- {- params: { id: FILE },- body: { newParentId: OTHER },- query: { drive: 'main' },- ip: '127.0.0.1',- } as never,+ { params: { id: FILE }, body: { newParentId: OTHER }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,res as never)expect(res.code).toBe(403)diff --git a/control-api/test/gfsResources.test.ts b/control-api/test/gfsResources.test.tsindex 82fb92716..520e71daf 100644--- a/control-api/test/gfsResources.test.ts+++ b/control-api/test/gfsResources.test.ts@@ -5,7 +5,6 @@ import {ResourcePatchError,applyResourcePatch,} from '../src/routes/gfs/resources.js'-const FILE = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'const SRC = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'const DEST = 'cccccccc-cccc-cccc-cccc-cccccccccccc'@@ -272,16 +271,9 @@ describe('applyResourcePatch — concurrency + guards', () => {})it('rejects destination live/kind/parent/version changes while acquiring row locks', async () => {- const mutations = [- (r: Record<string, ResRow>) => (r[DEST].version += 1),- (r: Record<string, ResRow>) => (r[DEST].kind = 'file'),- (r: Record<string, ResRow>) => (r[DEST].parent_resource_id = SRC),- (r: Record<string, ResRow>) => (r[DEST].deleted_at = '2026-07-17'),- ]+ const mutations = [(r: Record<string, ResRow>) => (r[DEST].version += 1), (r: Record<string, ResRow>) => (r[DEST].kind = 'file'), (r: Record<string, ResRow>) => (r[DEST].parent_resource_id = SRC), (r: Record<string, ResRow>) => (r[DEST].deleted_at = '2026-07-17')]for (const afterLock of mutations) {- await expect(- patch(mockDb({ afterLock }), operator, FILE, { newParentId: DEST })- ).rejects.toMatchObject({+ await expect(patch(mockDb({ afterLock }), operator, FILE, { newParentId: DEST })).rejects.toMatchObject({status: 412,code: 'precondition_failed',})@@ -301,9 +293,7 @@ describe('applyResourcePatch — concurrency + guards', () => {const db = mockDb()await patch(db, operator, FILE, { newParentId: DEST })const advisory = db.queries.findIndex(query => query.text.includes('pg_advisory_xact_lock'))- const rows = db.queries.findIndex(- query => query.text.includes('ORDER BY resource_id') && query.text.includes('FOR UPDATE')- )+ const rows = db.queries.findIndex(query => query.text.includes('ORDER BY resource_id') && query.text.includes('FOR UPDATE'))expect(advisory).toBeGreaterThanOrEqual(0)expect(rows).toBeGreaterThan(advisory)expect(db.queries[rows].values?.[0]).toEqual([FILE, SRC, DEST].sort())diff --git a/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts b/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.tsindex 8b09d1728..09a5fb963 100644--- a/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts+++ b/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts@@ -2,15 +2,15 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { createHash, randomBytes, randomUUID } from 'node:crypto'import type { Readable } from 'node:stream'import { Pool, type PoolClient } from 'pg'+import { initDb } from '../src/db.js'+import { applyResourcePatch } from '../src/routes/gfs/resources.js'+import type { GfsCaller } from '../src/routes/gfs/grants.js'import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'import {- type BlobWriter,GfsWriteService,+ type BlobWriter,type Transactor,} from '../../gfs-controller/src/db/writeStore.js'-import { initDb } from '../src/db.js'-import type { GfsCaller } from '../src/routes/gfs/grants.js'-import { applyResourcePatch } from '../src/routes/gfs/resources.js'const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -119,9 +119,7 @@ function writer(client: PoolClient, manifests = new PgBlobStagingStore(client)):}function deferred(): { promise: Promise<void>; resolve: () => void } {let resolve!: () => void- const promise = new Promise<void>(done => {- resolve = done- })+ const promise = new Promise<void>(done => { resolve = done })return { promise, resolve }}async function expectNoLiveNodeBelowTombstone(pool: Pool): Promise<void> {@@ -178,13 +176,11 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {name: 'concurrent',kind: 'directory',})- const deletion = writer(deleter)- .delete({- drive: tree.drive,- resourceId: tree.destinationA,- ifMatch: 0,- })- .catch(error => error as { code?: string })+ const deletion = writer(deleter).delete({+ drive: tree.drive,+ resourceId: tree.destinationA,+ ifMatch: 0,+ }).catch(error => error as { code?: string })await waitUntilBlocked(pool, deleterPid, creatorPid, 'create/delete')await creator.query('COMMIT')await expect(deletion).resolves.toMatchObject({ code: 'not_empty' })@@ -205,13 +201,11 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {const moverPid = Number((await mover.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)const deleterPid = Number((await deleter.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)expect(await move(mover, tree, tree.destinationA)).toBe(1)- const deletion = writer(deleter)- .delete({- drive: tree.drive,- resourceId: tree.destinationA,- ifMatch: 0,- })- .catch(error => error as { code?: string })+ const deletion = writer(deleter).delete({+ drive: tree.drive,+ resourceId: tree.destinationA,+ ifMatch: 0,+ }).catch(error => error as { code?: string })await waitUntilBlocked(pool, deleterPid, moverPid, 'move/delete')await mover.query('COMMIT')await expect(deletion).resolves.toMatchObject({ code: 'not_empty' })@@ -227,36 +221,23 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {it('rejects moving a directory below its descendant', async () => {const tree = await seedTree(pool, 'cycle')const descendant = randomUUID()- await pool.query(- `INSERT INTO gfs_resources+ await pool.query(`INSERT INTO gfs_resources(resource_id,drive,parent_resource_id,name,kind,path_cache,version,bytes)VALUES ($1,$2,$3,'descendant','directory','/source/descendant',0,0)`,- [descendant, tree.drive, tree.source]- )+ [descendant, tree.drive, tree.source])const client = await pool.connect()try {await begin(client)- await expect(- applyResourcePatch(- client,- operator,- tree.drive,- tree.source,- { newParentId: descendant },- async () => undefined- )- ).rejects.toMatchObject({ code: 'path_invalid' })+ await expect(applyResourcePatch(+ client, operator, tree.drive, tree.source, { newParentId: descendant }, async () => undefined+ )).rejects.toMatchObject({ code: 'path_invalid' })} finally {await client.query('ROLLBACK').catch(() => undefined)client.release()}const source = await pool.query(- 'SELECT parent_resource_id,path_cache,version FROM gfs_resources WHERE resource_id=$1',- [tree.source]- )- expect(source.rows).toEqual([- { parent_resource_id: tree.root, path_cache: '/source', version: 0 },- ])+ 'SELECT parent_resource_id,path_cache,version FROM gfs_resources WHERE resource_id=$1', [tree.source])+ expect(source.rows).toEqual([{ parent_resource_id: tree.root, path_cache: '/source', version: 0 }])})it('atomically refreshes path_cache for every node in a moved subtree', async () => {@@ -273,34 +254,20 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {try {await begin(client)await applyResourcePatch(- client,- operator,- tree.drive,- tree.source,- { newParentId: tree.destinationA },- async () => undefined- )- const beforeCommit = await pool.query(- `SELECT path_cache FROM gfs_resources- WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`,- [[tree.source, tree.child, nested, leaf]]+ client, operator, tree.drive, tree.source, { newParentId: tree.destinationA }, async () => undefined)+ const beforeCommit = await pool.query(`SELECT path_cache FROM gfs_resources+ WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`, [[tree.source, tree.child, nested, leaf]])expect(beforeCommit.rows.map(row => row.path_cache)).toEqual([- '/source',- '/source/child.txt',- '/source/nested',- '/source/nested/leaf.txt',+ '/source', '/source/child.txt', '/source/nested', '/source/nested/leaf.txt',])await client.query('COMMIT')} finally {await client.query('ROLLBACK').catch(() => undefined)client.release()}- const paths = await pool.query(- `SELECT name,path_cache FROM gfs_resources- WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`,- [[tree.source, tree.child, nested, leaf]]- )+ const paths = await pool.query(`SELECT name,path_cache FROM gfs_resources+ WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`, [[tree.source, tree.child, nested, leaf]])expect(paths.rows).toEqual([{ name: 'source', path_cache: '/destination-a/source' },{ name: 'child.txt', path_cache: '/destination-a/source/child.txt' },@@ -326,13 +293,11 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {`SELECT parent_resource_id,path_cache,version FROM gfs_resources WHERE resource_id=$1`,[tree.child])- expect(final.rows).toEqual([- {- parent_resource_id: tree.destinationB,- path_cache: '/destination-b/child.txt',- version: 2,- },- ])+ expect(final.rows).toEqual([{+ parent_resource_id: tree.destinationB,+ path_cache: '/destination-b/child.txt',+ version: 2,+ }])} finally {await first.query('ROLLBACK').catch(() => undefined)await second.query('ROLLBACK').catch(() => undefined)diff --git a/control-api/test/routes.overview.test.ts b/control-api/test/routes.overview.test.tsindex 289cbf827..797dff7fc 100644--- a/control-api/test/routes.overview.test.ts+++ b/control-api/test/routes.overview.test.ts@@ -1,136 +1,135 @@-import { describe, expect, it, vi } from 'vitest'-import express from 'express'-import request from 'supertest'-import { createAdminHostsOverviewRouter } from '../src/routes/admin/hostsOverview.js'-import { MockGateway } from './mockGateway.js'--describe('routes/admin.hostsOverview', () => {- it('returns hosts overview list and single host overview', async () => {- const gateway = new MockGateway('mcp-server')+import express from "express";+import request from "supertest";+import { describe, expect, it, vi } from "vitest";+import { createAdminHostsOverviewRouter } from "../src/routes/admin/hostsOverview.js";+import { MockGateway } from "./mockGateway.js";++describe("routes/admin.hostsOverview", () => {+ it("returns hosts overview list and single host overview", async () => {+ const gateway = new MockGateway("mcp-server");await gateway.createResource(- 'hosts',- { metadata: { name: 'host-a', namespace: 'mcp-host' }, spec: { contextRef: 'ctx-a' } },- 'mcp-host'- )+ "hosts",+ { metadata: { name: "host-a", namespace: "mcp-host" }, spec: { contextRef: "ctx-a" } },+ "mcp-host"+ );await gateway.createResource(- 'contexts',- {- metadata: { name: 'ctx-a', namespace: 'mcp-server' },- spec: { contextId: 'ctx-a', mcpServers: [] },- },- 'mcp-server'- )+ "contexts",+ { metadata: { name: "ctx-a", namespace: "mcp-server" }, spec: { contextId: "ctx-a", mcpServers: [] } },+ "mcp-server"+ );- const app = express()- app.use(createAdminHostsOverviewRouter(gateway as never))+ const app = express();+ app.use(createAdminHostsOverviewRouter(gateway as never));// Hardened: no ?namespace= on requests; route uses config.hostsNamespace internally.- const listRes = await request(app).get('/admin/hosts-overview').expect(200)- expect(listRes.body.items).toHaveLength(1)- expect(listRes.body.items[0].host.spec.contextRef).toBe('ctx-a')+ const listRes = await request(app).get("/admin/hosts-overview").expect(200);+ expect(listRes.body.items).toHaveLength(1);+ expect(listRes.body.items[0].host.spec.contextRef).toBe("ctx-a");expect(listRes.body.agents).toEqual([{- name: 'host-a',- namespace: 'mcp-host',- displayName: 'host-a',+ name: "host-a",+ namespace: "mcp-host",+ displayName: "host-a",active: true,- gfsSubject: { type: 'host', id: '1st:mcp-host/host-a' },+ gfsSubject: { type: "host", id: "1st:mcp-host/host-a" },},- ])+ ]);- const singleRes = await request(app).get('/admin/hosts/host-a/overview').expect(200)- expect(singleRes.body.host.metadata.name).toBe('host-a')- expect(singleRes.body.agent.gfsSubject.id).toBe('1st:mcp-host/host-a')- })+ const singleRes = await request(app).get("/admin/hosts/host-a/overview").expect(200);+ expect(singleRes.body.host.metadata.name).toBe("host-a");+ expect(singleRes.body.agent.gfsSubject.id).toBe("1st:mcp-host/host-a");+ });- it('keeps overview compatibility while directory excludes invalid Host identities', async () => {+ it("keeps overview compatibility while directory excludes invalid Host identities", async () => {const hosts = [- { metadata: { name: 'visible', namespace: 'mcp-host' }, spec: { host: 'Visible' } },- { metadata: { name: 'disabled', namespace: 'mcp-host' }, spec: { enabled: false } },+ { metadata: { name: "visible", namespace: "mcp-host" }, spec: { host: "Visible" } },+ { metadata: { name: "disabled", namespace: "mcp-host" }, spec: { enabled: false } },{metadata: {- name: 'deleted',- namespace: 'mcp-host',- deletionTimestamp: '2026-07-17T12:00:00Z',+ name: "deleted",+ namespace: "mcp-host",+ deletionTimestamp: "2026-07-17T12:00:00Z",},spec: {},},- { metadata: { name: 'other', namespace: 'sandbox-recipes' }, spec: {} },- ]+ { metadata: { name: "other", namespace: "sandbox-recipes" }, spec: {} },+ ];const gateway = {listResource: vi.fn(async () => hosts),getHostOverview: vi.fn(async (name: string, namespace: string) => ({host: hosts.find(host => host.metadata.name === name),namespace,})),- }+ };- const app = express()- app.use(createAdminHostsOverviewRouter(gateway as never))+ const app = express();+ app.use(createAdminHostsOverviewRouter(gateway as never));- const res = await request(app).get('/admin/hosts-overview').expect(200)- expect(res.body.items).toHaveLength(4)+ const res = await request(app).get("/admin/hosts-overview").expect(200);+ expect(res.body.items).toHaveLength(4);expect(res.body.agents).toEqual([{- name: 'visible',- namespace: 'mcp-host',- displayName: 'Visible',+ name: "visible",+ namespace: "mcp-host",+ displayName: "Visible",active: true,- gfsSubject: { type: 'host', id: '1st:mcp-host/visible' },+ gfsSubject: { type: "host", id: "1st:mcp-host/visible" },},- ])- })+ ]);+ });- it('returns 500 when host overview fails', async () => {+ it("returns 500 when host overview fails", async () => {const gateway = {- listResource: vi.fn(async () => [{ metadata: { name: 'host-a', namespace: 'mcp-host' } }]),+ listResource: vi.fn(async () => [{ metadata: { name: "host-a", namespace: "mcp-host" } }]),getHostOverview: vi.fn(async () => {- throw new Error('overview-failed')- }),- }-- const app = express()- app.use(createAdminHostsOverviewRouter(gateway as never))- app.use(- (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {- res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })- }- )-- const res = await request(app).get('/admin/hosts-overview').expect(500)- expect(res.body.error).toBe('overview-failed')- })+ throw new Error("overview-failed");+ })+ };++ const app = express();+ app.use(createAdminHostsOverviewRouter(gateway as never));+ app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : "unknown" });+ });++ const res = await request(app).get("/admin/hosts-overview").expect(500);+ expect(res.body.error).toBe("overview-failed");+ });// ── Namespace audit: caller namespace is silently ignored ────────────────- it('silently ignores ?namespace= query parameter and uses config namespace', async () => {+ it("silently ignores ?namespace= query parameter and uses config namespace", async () => {const gateway = {listResource: vi.fn(async () => []),getHostOverview: vi.fn(),- }- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})- const app = express()- app.use(createAdminHostsOverviewRouter(gateway as never))+ };+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ const app = express();+ app.use(createAdminHostsOverviewRouter(gateway as never));// Namespace in query string is silently ignored — request succeeds (200, not 400)const listRes = await request(app)- .get('/admin/hosts-overview?namespace=control-plane')- .expect(200)- expect(listRes.body.items).toEqual([])- expect(listRes.body.agents).toEqual([])+ .get("/admin/hosts-overview?namespace=control-plane")+ .expect(200);+ expect(listRes.body.items).toEqual([]);+ expect(listRes.body.agents).toEqual([]);const singleRes = await request(app)- .get('/admin/hosts/host-a/overview?namespace=control-plane')- .expect(200)+ .get("/admin/hosts/host-a/overview?namespace=control-plane")+ .expect(200);// Gateway was called despite namespace in query (it's silently ignored)- expect(gateway.listResource).toHaveBeenCalled()- expect(gateway.getHostOverview).toHaveBeenCalled()+ expect(gateway.listResource).toHaveBeenCalled();+ expect(gateway.getHostOverview).toHaveBeenCalled();// Security audit was logged- expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('"alert":"SECURITY"'))- expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('"vector":"query-param"'))-- warnSpy.mockRestore()- })-})+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('"alert":"SECURITY"'),+ );+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('"vector":"query-param"'),+ );++ warnSpy.mockRestore();+ });+});diff --git a/control-api/test/routes.profileAdmin.test.ts b/control-api/test/routes.profileAdmin.test.tsindex 88262e5eb..483b6a66e 100644--- a/control-api/test/routes.profileAdmin.test.ts+++ b/control-api/test/routes.profileAdmin.test.ts@@ -200,9 +200,7 @@ describe('routes/profileAdmin', () => {return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]}if (plural === 'hosts') {- return [- { metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } },- ]+ return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]}return []})@@ -245,9 +243,7 @@ describe('routes/profileAdmin', () => {return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]}if (plural === 'hosts') {- return [- { metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } },- ]+ return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]}return []})diff --git a/control-ui/components/__tests__/GovernedTraceSurface.test.tsx b/control-ui/components/__tests__/GovernedTraceSurface.test.tsxindex 1a984cab3..97b8e7025 100644--- a/control-ui/components/__tests__/GovernedTraceSurface.test.tsx+++ b/control-ui/components/__tests__/GovernedTraceSurface.test.tsx@@ -1,11 +1,11 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import {- type InfrastructureCostScopeCatalog,getGovernedTraceEvents,getInfrastructureCostScopes,getInfrastructureTraceCosts,isTraceCostsUnavailable,+ type InfrastructureCostScopeCatalog,} from '@lib/governedTrace'import { GovernedTraceSurface } from '../GovernedTraceSurface'diff --git a/control-ui/e2e/host-stateless-channel-rejection.spec.ts b/control-ui/e2e/host-stateless-channel-rejection.spec.tsindex 3467625f3..ecf8655fe 100644--- a/control-ui/e2e/host-stateless-channel-rejection.spec.ts+++ b/control-ui/e2e/host-stateless-channel-rejection.spec.ts@@ -39,8 +39,8 @@* 4. E2E_KUBECONTEXT (or CONTEXT) — an allowed kubectl context (clerum-test /* clerum-codex-* / gke_<project>_<zone>_<cluster>). Passed to every kubectl call.*/-import { type Page, expect, test } from '@playwright/test'import { execFileSync } from 'node:child_process'+import { type Page, expect, test } from '@playwright/test'const BASE_UI = process.env.CONTROL_UI_URL || 'http://localhost:3000'const ADMIN_USER = process.env.ADMIN_USER || 'admin'@@ -132,8 +132,7 @@ test.describe('operator sees the stateless × CommunicationChannel hard-rejectiotest.beforeAll(() => {// Fail loud on missing prerequisites rather than skipping silently.if (!HOST) throw new Error('E2E_STATELESS_HOST must name a dedicated stateless Host.')- if (!KUBECONTEXT)- throw new Error('E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context.')+ if (!KUBECONTEXT) throw new Error('E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context.')const host = getHostJson()// Guard: the target must actually be a stateless Host, or the whole scenario is invalid.const statelessRaw = kubectl([@@ -174,9 +173,7 @@ test.describe('operator sees the stateless × CommunicationChannel hard-rejectio'HCC did not hard-reject the stateless Host after the CommunicationChannel was applied ' +'(requires the Addendum-6 executor fix deployed).',})- .toMatch(- /"effectiveMode":"stateful".*"rejected":true|"rejected":true.*"effectiveMode":"stateful"/- )+ .toMatch(/"effectiveMode":"stateful".*"rejected":true|"rejected":true.*"effectiveMode":"stateful"/)const rejectionMessage = getHostJson().rejectionMessageexpect(rejectionMessage, 'StatelessEnableRejected condition must carry a message').toBeTruthy()@@ -202,9 +199,9 @@ test.describe('operator sees the stateless × CommunicationChannel hard-rejectio// (1) the warning banner container carries the reason verbatimawait expect(rejectionBanner).toContainText(rejectionMessage as string, { timeout: 20_000 })// (2) the lifecycle chip is a second visibility surface — assert it deliberately- await expect(page.locator('.cu-chip', { hasText: rejectionMessage as string })).toBeVisible({- timeout: 20_000,- })+ await expect(+ page.locator('.cu-chip', { hasText: rejectionMessage as string })+ ).toBeVisible({ timeout: 20_000 })// Disassociation recovery: remove the channel; HCC clears the rejection.// Strict delete (not the best-effort cleanup helper) so a real failure herediff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.tsindex c0dc1fd0b..7670eaa97 100644--- a/desktop-app/src/__tests__/appService.gfs.test.ts+++ b/desktop-app/src/__tests__/appService.gfs.test.ts@@ -91,9 +91,9 @@ describe('AppService GFS delegation subject boundary', () => {async subjectKey => {const service = gfsService()- await expect(service.grantGfs(RESOURCE_ID, [subjectKey], ['read'], 'main')).rejects.toThrow(- 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>'- )+ await expect(+ service.grantGfs(RESOURCE_ID, [subjectKey], ['read'], 'main')+ ).rejects.toThrow('subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>')await expect(service.createGfsShare(RESOURCE_ID, [subjectKey], 'main')).rejects.toThrow('subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>')diff --git a/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-copy.test.tsindex 47a40cc34..d00cfa1b7 100644--- a/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts@@ -5,8 +5,6 @@* fixture helper performs the agent mutations under test.*/import { type Locator, type Page, expect, test } from '@playwright/test'-import { exactNameFilter } from './helpers/agentLocators'-import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'import {type AgentGfsCopyFixtures,assertGfsInfraHealthy,@@ -19,6 +17,8 @@ import {revokeGfsGrantViaControlApi,seedAgentGfsCopyFixtures,} from './helpers/gfsFixtures'+import { exactNameFilter } from './helpers/agentLocators'+import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'import { launchAndLogin } from './workflowUi'@@ -57,13 +57,7 @@ async function openExactAgent(const breadcrumb = page.getByRole('navigation', { name: 'Chat breadcrumb' }).getByText(agentName, { exact: true })- if (- !(await boundSwitcher- .or(breadcrumb)- .first()- .isVisible()- .catch(() => false))- ) {+ if (!(await boundSwitcher.or(breadcrumb).first().isVisible().catch(() => false))) {await switcher.first().click()await page.getByRole('menuitem', { name: agentName, exact: true }).click()}@@ -113,10 +107,12 @@ async function sendAgentTurn(page: Page, prompt: string): Promise<Locator> {console.warn(`[gfs-agent-copy] "Retry last send" pressed (attempt ${sendRetries}/3) for turn: ${turnLabel}`)- test.info().annotations.push({- type: 'retry-last-send',- description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,- })+ test+ .info()+ .annotations.push({+ type: 'retry-last-send',+ description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,+ })await retrySend.click()continue}@@ -166,9 +162,7 @@ async function expectToolForbidden(stepper: Locator, name: string): Promise<voidconst row = toolRow(stepper, name)await expect(row).toBeVisible({ timeout: 15_000 })await expect(row.locator('.stepper-step-fn')).toContainText(name)- await expect(row.locator('.stepper-step-duration.state-error')).toContainText(- /gfsc 403.*forbidden/i- )+ await expect(row.locator('.stepper-step-duration.state-error')).toContainText(/gfsc 403.*forbidden/i)await expect(row).not.toContainText(/gfsc 503|not_mounted/i)await expect(stepper).not.toContainText(SENSITIVE_OUTPUT)}@@ -181,9 +175,7 @@ async function expectToolConflict(stepper: Locator, name: string): Promise<void>const row = toolRow(stepper, name)await expect(row).toBeVisible({ timeout: 15_000 })await expect(row.locator('.stepper-step-fn')).toContainText(name)- await expect(row.locator('.stepper-step-duration.state-error')).toContainText(- /gfsc 409.*conflict/i- )+ await expect(row.locator('.stepper-step-duration.state-error')).toContainText(/gfsc 409.*conflict/i)await expect(row).not.toContainText(/gfsc 503|not_mounted/i)await expect(stepper).not.toContainText(SENSITIVE_OUTPUT)}@@ -210,12 +202,7 @@ async function expectCopyPublicOutput(stepper: Locator): Promise<void> {}function comparableTree(root: ReturnType<typeof getGfsTreeSnapshot>) {- return root.map(({ relativePath, kind, bytes, content }) => ({- relativePath,- kind,- bytes,- content,- }))+ return root.map(({ relativePath, kind, bytes, content }) => ({ relativePath, kind, bytes, content }))}async function openFilesBrowser(page: Page): Promise<Locator> {@@ -240,9 +227,7 @@ async function browseSourceTree(page: Page, fixtures: AgentGfsCopyFixtures): Proasync function browseDestinationTree(page: Page, fixtures: AgentGfsCopyFixtures): Promise<void> {const browser = await openFilesBrowser(page)await browser.getByRole('button', { name: fixtures.tree.destinationName, exact: true }).click()- await expect(- browser.getByRole('button', { name: fixtures.fileCopyName, exact: true })- ).toBeVisible()+ await expect(browser.getByRole('button', { name: fixtures.fileCopyName, exact: true })).toBeVisible()await browser.getByRole('button', { name: fixtures.renamedFolderName, exact: true }).click()await expect(browser.getByRole('button', { name: 'nested', exact: true })).toBeVisible()await browser.getByRole('button', { name: 'nested', exact: true }).click()@@ -282,12 +267,11 @@ test.describe('GFS per-agent native Copy and immediate grant enforcement (issue).toHaveLength(1)expect(sourceAclShareRecords.filter(- record => record.kind === 'grant' && record.row.subject_id === fixtures.sourceShareSubjectId+ record =>+ record.kind === 'grant' && record.row.subject_id === fixtures.sourceShareSubjectId)).toHaveLength(0)- expect(getGfsTreeAclShareCounts(fixtures.tree.sourceResourceId).shares).toBeGreaterThanOrEqual(- 1- )+ expect(getGfsTreeAclShareCounts(fixtures.tree.sourceResourceId).shares).toBeGreaterThanOrEqual(1)const { app, page } = await launchAndLogin(OWNER_EMAIL)try {await test.step('Agent A copies one file through the native tool', async () => {@@ -310,16 +294,9 @@ test.describe('GFS per-agent native Copy and immediate grant enforcement (issueexpect(copied).not.toBeNull()expect(copied?.resourceId).not.toBe(fixtures.tree.standaloneFileResourceId)const copiedTree = getGfsTreeSnapshot(copied!.resourceId)- const sourceFile = sourceBefore.find(- node => node.resourceId === fixtures.tree.standaloneFileResourceId- )+ const sourceFile = sourceBefore.find(node => node.resourceId === fixtures.tree.standaloneFileResourceId)expect(comparableTree(copiedTree)).toEqual([- {- relativePath: '.',- kind: 'file',- bytes: sourceFile!.bytes,- content: sourceFile!.content,- },+ { relativePath: '.', kind: 'file', bytes: sourceFile!.bytes, content: sourceFile!.content },])expect(getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)).toEqual(sourceAclShareBefore)expect(getGfsTreeAclShareCounts(copied!.resourceId)).toEqual({ grants: 0, shares: 0 })diff --git a/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.tsindex 951290afe..612401489 100644--- a/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts@@ -38,15 +38,6 @@* - Infra guard: gfsc unhealthy ⇒ the suite THROWS (never skips, never mocks).*/import { type Locator, type Page, expect, test } from '@playwright/test'-import { getGfsHostGrantsUnderTree } from '../../../tests/e2e/gfsCopyFixtures'-import {- type GfsFileFixture,- cleanupGfsFixture,- getE2EUserId,- seedGfsFileFixture,- seedGfsGrant,- uniqueGfsFixtureName,-} from '../../../tests/e2e/gfsUiFixtures'import { exactNameFilter } from './helpers/agentLocators'import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'import {@@ -56,6 +47,15 @@ import {getGfsTreeSnapshot,gfsGrantRevokeAuditCount,} from './helpers/gfsFixtures'+import {+ type GfsFileFixture,+ cleanupGfsFixture,+ getE2EUserId,+ seedGfsFileFixture,+ seedGfsGrant,+ uniqueGfsFixtureName,+} from '../../../tests/e2e/gfsUiFixtures'+import { getGfsHostGrantsUnderTree } from '../../../tests/e2e/gfsCopyFixtures'import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'import { launchAndLogin } from './workflowUi'@@ -157,13 +157,7 @@ async function openExactAgent(const breadcrumb = page.getByRole('navigation', { name: 'Chat breadcrumb' }).getByText(agentName, { exact: true })- if (- !(await boundSwitcher- .or(breadcrumb)- .first()- .isVisible()- .catch(() => false))- ) {+ if (!(await boundSwitcher.or(breadcrumb).first().isVisible().catch(() => false))) {await switcher.first().click()await page.getByRole('menuitem', { name: agentName, exact: true }).click()}@@ -346,9 +340,7 @@ async function openManageForFixtureFolder(await expect(browser.getByRole('button', { name: fixtures.folder.fileName, exact: true })).toBeVisible({ timeout: 20_000 })- await browser- .getByRole('button', { name: `Options for ${fixtures.folder.name}`, exact: true })- .click()+ await browser.getByRole('button', { name: `Options for ${fixtures.folder.name}`, exact: true }).click()await browser.getByRole('menuitem', { name: 'Manage', exact: true }).click()const dialog = page.getByRole('dialog', { name: `Manage folder ${fixtures.folder.name}` })await expect(dialog).toBeVisible({ timeout: 15_000 })@@ -468,7 +460,9 @@ async function grantMultipleAgentsViaManageModal(// Plural toast proves the batch was accepted as a unit (singular would mean the// multi-select collapsed to one subject — the exact regression this guards).await expect(- page.getByText(`Access granted to ${opts.agentNames.length} agents`, { exact: true }).first()+ page+ .getByText(`Access granted to ${opts.agentNames.length} agents`, { exact: true })+ .first()).toBeVisible({ timeout: 20_000 })// list-after-write: every grantee now has a Revoke row (grants GET returned all N).for (const name of opts.agentNames) {@@ -543,10 +537,7 @@ test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enfoawait closeManageDialog(page, dialog)// Business truth: exactly one host grant row for A on the folder,// read+write, inherit true — and still none for B.- const grantsA = getGfsHostGrantsUnderTree(- fixtures.folder.resourceId,- fixtures.agentA.subjectId- )+ const grantsA = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)expect(grantsA).toHaveLength(1)expect(grantsA[0]!.resourceId).toBe(fixtures.folder.resourceId)expect([...grantsA[0]!.permissions].sort()).toEqual(['read', 'write'])@@ -631,19 +622,13 @@ test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enfoincludeWrite: false,})await closeManageDialog(page, dialog)- const grantsB = getGfsHostGrantsUnderTree(- fixtures.folder.resourceId,- fixtures.agentB.subjectId- )+ const grantsB = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)expect(grantsB).toHaveLength(1)expect(grantsB[0]!.resourceId).toBe(fixtures.folder.resourceId)expect(grantsB[0]!.permissions).toEqual(['read'])expect(grantsB[0]!.inherit).toBe(true)// A's Test-1 grant is untouched by B's grant.- const grantsA = getGfsHostGrantsUnderTree(- fixtures.folder.resourceId,- fixtures.agentA.subjectId- )+ const grantsA = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)expect(grantsA).toHaveLength(1)expect([...grantsA[0]!.permissions].sort()).toEqual(['read', 'write'])})@@ -709,7 +694,10 @@ test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enfo'verbatim. Do not answer from memory — attempt the read with your Clerum GFS ' +'tools even if the file is not in your listing.')- await expectNoDisclosureDenial(turn, [fixtures.originalSentinel, fixtures.modifiedSentinel])+ await expectNoDisclosureDenial(turn, [+ fixtures.originalSentinel,+ fixtures.modifiedSentinel,+ ])// Same-runtime proof: pod UID + startTime are unchanged across the// revoke and the denied retry — live cache invalidation, not a restart.expect(getManagedAgentPodIdentity(fixtures.agentA)).toBe(runtimeBefore)@@ -724,10 +712,7 @@ test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enfo)assertNoInfraFailureShape(turn.responseText)await expectReadWithSentinel(turn.stepper, fixtures.modifiedSentinel)- const grantsB = getGfsHostGrantsUnderTree(- fixtures.folder.resourceId,- fixtures.agentB.subjectId- )+ const grantsB = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)expect(grantsB).toHaveLength(1)expect(grantsB[0]!.permissions).toEqual(['read'])})diff --git a/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.tsindex 130de19e9..8027f6596 100644--- a/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts@@ -1,4 +1,8 @@-import { UUID_RE, runControlPostgresSql, sqlLiteral } from '../../../../tests/e2e/gfsUiFixtures'+import {+ UUID_RE,+ runControlPostgresSql,+ sqlLiteral,+} from '../../../../tests/e2e/gfsUiFixtures'/*** Named setup precondition: shares may target users/teams, never managed Hostdiff --git a/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts b/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.tsindex 54bd51f4c..9394beecb 100644--- a/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts@@ -46,15 +46,11 @@ function discoverManagedGfsAgentCandidates(): {const output = kubectlOut(['get', 'secrets', '-A', '-o', `go-template=${template}`])const bySubject = new Map<string, ManagedGfsAgent>()const candidateErrors: CandidateError[] = []- for (const line of output- .split('\n')- .map(value => value.trim())- .filter(Boolean)) {+ for (const line of output.split('\n').map(value => value.trim()).filter(Boolean)) {const [annotatedSubject, hostUid, hostGeneration] = line.split('\t')- const match =- /^host:1st:([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)\/([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)$/.exec(- annotatedSubject ?? ''- )+ const match = /^host:1st:([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)\/([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)$/.exec(+ annotatedSubject ?? ''+ )if (!match || !hostUid || !/^\d+$/.test(hostGeneration ?? '')) continueconst namespace = match[1]!const name = match[2]!@@ -83,8 +79,7 @@ function discoverManagedGfsAgentCandidates(): {continue}const [activeUid, activeGeneration, deleting, disabled] = hostState.split('\t')- if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled)- continue+ if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled) continuebySubject.set(subjectId, { name, namespace, subjectId })}if (bySubject.size === 0 && candidateErrors.length > 0) {diff --git a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.tsindex 4ba819635..642d2faec 100644--- a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts@@ -1,19 +1,10 @@/** Exact-subject GFS fixtures for the #775 regression and #797 Copy journey. */-import { request } from '@playwright/test'-import {- type GfsCopyTreeFixture,- cleanupGfsCopyTreeFixture,- getGfsHostGrantsUnderTree,- getGfsTreeAclShareCounts,- getGfsTreeSnapshot,- seedGfsCopyTreeFixture,-} from '../../../../tests/e2e/gfsCopyFixtures'import {type GfsFileFixture,cleanupGfsFixture,countGfsLiveChildrenByName,- getE2EUserId,getGfsChildResourceSummary,+ getE2EUserId,kubectlOut,runControlPostgresSql,seedGfsFileFixture,@@ -21,12 +12,21 @@ import {sqlLiteral,uniqueGfsFixtureName,} from '../../../../tests/e2e/gfsUiFixtures'-import { seedIssue797SourceShare } from './gfsAclShareFixtures'import {- type ManagedGfsAgent,+ type GfsCopyTreeFixture,+ cleanupGfsCopyTreeFixture,+ getGfsHostGrantsUnderTree,+ getGfsTreeAclShareCounts,+ getGfsTreeSnapshot,+ seedGfsCopyTreeFixture,+} from '../../../../tests/e2e/gfsCopyFixtures'+import { request } from '@playwright/test'+import {discoverManagedGfsAgent,discoverManagedGfsAgents,+ type ManagedGfsAgent,} from './gfsAgentDiscovery'+import { seedIssue797SourceShare } from './gfsAclShareFixtures'export {discoverManagedGfsAgent,@@ -143,36 +143,21 @@ export function seedAgentGfsCopyFixtures(ownerEmail: string): AgentGfsCopyFixturgrantedBy: 'e2e:issue-797-agent-a',})seedGfsGrant({- resourceId: tree.sourceResourceId,- subjectType: 'host',- subjectId: agentB.subjectId,- permissions: ['read'],- inherit: false,- grantedBy: 'e2e:issue-797-agent-b-root-only',+ resourceId: tree.sourceResourceId, subjectType: 'host', subjectId: agentB.subjectId,+ permissions: ['read'], inherit: false, grantedBy: 'e2e:issue-797-agent-b-root-only',})seedGfsGrant({- resourceId: tree.destinationResourceId,- subjectType: 'host',- subjectId: agentB.subjectId,- permissions: ['read', 'write'],- inherit: true,- grantedBy: 'e2e:issue-797-agent-b-destination',+ resourceId: tree.destinationResourceId, subjectType: 'host', subjectId: agentB.subjectId,+ permissions: ['read', 'write'], inherit: true, grantedBy: 'e2e:issue-797-agent-b-destination',})const agentBSource = getGfsHostGrantsUnderTree(tree.sourceResourceId, agentB.subjectId)- if (- agentBSource.length !== 1 ||- agentBSource[0]?.resourceId !== tree.sourceResourceId ||- agentBSource[0].inherit ||- agentBSource[0].permissions.join(',') !== 'read'- ) {+ if (agentBSource.length !== 1 || agentBSource[0]?.resourceId !== tree.sourceResourceId ||+ agentBSource[0].inherit || agentBSource[0].permissions.join(',') !== 'read') {throw new Error('Agent B fixture must have root-only source read and no descendant grant')}const agentBDest = getGfsHostGrantsUnderTree(tree.destinationResourceId, agentB.subjectId)- if (- agentBDest.length !== 1 ||- !agentBDest[0]?.inherit ||- agentBDest[0].permissions.join(',') !== 'read,write'- ) {+ if (agentBDest.length !== 1 || !agentBDest[0]?.inherit ||+ agentBDest[0].permissions.join(',') !== 'read,write') {throw new Error('Agent B fixture must have destination read/write')}const destinationGrantId = seedGfsGrant({@@ -255,9 +240,7 @@ export async function revokeGfsGrantViaControlApi(grantId: string): Promise<void},})if (!response.ok()) {- throw new Error(- `audited GFS revoke failed with HTTP ${response.status()}: ${await response.text()}`- )+ throw new Error(`audited GFS revoke failed with HTTP ${response.status()}: ${await response.text()}`)}} finally {await api.dispose()diff --git a/desktop-app/test/e2e-playwright/stateless-wake.test.ts b/desktop-app/test/e2e-playwright/stateless-wake.test.tsindex d94b0c954..dddb6c05e 100644--- a/desktop-app/test/e2e-playwright/stateless-wake.test.ts+++ b/desktop-app/test/e2e-playwright/stateless-wake.test.ts@@ -774,7 +774,9 @@ async function expectAssistantMarkerRendered(// usable model list (ModelSelector returns null until data loads and renders a// non-interactive chip only when degraded), so a visible interactive picker with// selectable options is itself the proof.-async function exerciseVisibleModelPicker(appPage: import('@playwright/test').Page): Promise<void> {+async function exerciseVisibleModelPicker(+ appPage: import('@playwright/test').Page+): Promise<void> {const trigger = appPage.getByRole('button', { name: /^Model — / })await expect(trigger,@@ -881,12 +883,13 @@ test('Scenario 4 — concurrent session/model/message on a COLD wake, then two-c// exercise of the coordinator dedup (the Desktop mirror of bash Test 6). The// prewarm's status is the cold/warm oracle; the UI waking-state affordance is NOT// used for the mode because a transparent sub-hold-deadline wake never renders it.- const [prewarmDuringColdWake, sessionsDuringColdWake, modelsDuringColdWake] = await Promise.all([- probeStatelessPrewarm(appPage),- readStatelessSessionIds(appPage),- probeStatelessHostModels(appPage),- sendButton.click(),- ])+ const [prewarmDuringColdWake, sessionsDuringColdWake, modelsDuringColdWake] =+ await Promise.all([+ probeStatelessPrewarm(appPage),+ readStatelessSessionIds(appPage),+ probeStatelessHostModels(appPage),+ sendButton.click(),+ ])expect(sessionsDuringColdWake.error,`[stateless-wake] concurrent listSessions during the COLD wake must not 403/fail — ${sessionsDuringColdWake.error}`diff --git a/desktop-app/test/gfsAclShareFixtures.test.ts b/desktop-app/test/gfsAclShareFixtures.test.tsindex baad33750..3db3831d2 100644--- a/desktop-app/test/gfsAclShareFixtures.test.ts+++ b/desktop-app/test/gfsAclShareFixtures.test.ts@@ -1,8 +1,4 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import {- getGfsTreeAclShareRows,- seedIssue797SourceShare,-} from './e2e-playwright/helpers/gfsAclShareFixtures'const runControlPostgresSqlMock = vi.hoisted(() => vi.fn())@@ -12,6 +8,11 @@ vi.mock('../../tests/e2e/gfsUiFixtures', () => ({sqlLiteral: (value: string) => `'${value.replace(/'/g, "''")}'`,}))+import {+ getGfsTreeAclShareRows,+ seedIssue797SourceShare,+} from './e2e-playwright/helpers/gfsAclShareFixtures'+describe('issue #797 GFS ACL/share fixture evidence', () => {beforeEach(() => runControlPostgresSqlMock.mockReset())diff --git a/desktop-app/test/gfsFixtureDiscovery.test.ts b/desktop-app/test/gfsFixtureDiscovery.test.tsindex dd3e75c99..e9f517c22 100644--- a/desktop-app/test/gfsFixtureDiscovery.test.ts+++ b/desktop-app/test/gfsFixtureDiscovery.test.ts@@ -1,8 +1,4 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import {- discoverManagedGfsAgent,- discoverManagedGfsAgents,-} from './e2e-playwright/helpers/gfsFixtures'const execFileSyncMock = vi.hoisted(() => vi.fn())@@ -10,6 +6,11 @@ vi.mock('node:child_process', () => ({execFileSync: execFileSyncMock,}))+import {+ discoverManagedGfsAgent,+ discoverManagedGfsAgents,+} from './e2e-playwright/helpers/gfsFixtures'+describe('discoverManagedGfsAgents', () => {const context = 'clerum-codex-gfs-fixture-test'let secretRows: stringdiff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.tsindex 18d9442a5..dac8fbd92 100644--- a/desktop-app/test/gfsUriHandler.test.ts+++ b/desktop-app/test/gfsUriHandler.test.ts@@ -1,4 +1,5 @@import { describe, expect, it, vi } from 'vitest'+import { ApiError } from '../src/httpClient.js'import {GfsClient,type GfsTransport,@@ -7,7 +8,6 @@ import {parseGfsUri,parseSubjectKey,} from '../src/gfs/uriHandler.js'-import { ApiError } from '../src/httpClient.js'/*** P2-S06 — Desktop gfs:// resolve + read. Acceptance: a gfs://<drive>/<rid> linkdiff --git a/desktop-app/test/rpcTokenManager.test.ts b/desktop-app/test/rpcTokenManager.test.tsindex 7e603ad3c..4126151c4 100644--- a/desktop-app/test/rpcTokenManager.test.ts+++ b/desktop-app/test/rpcTokenManager.test.ts@@ -1,115 +1,113 @@-import { describe, expect, it, vi } from 'vitest'-import type { AuthClient } from '../src/authClient.js'-import { RpcTokenManager } from '../src/rpcTokenManager.js'--vi.mock('../src/config.js', () => ({- config: { requestTimeoutMs: 5000, externalRestApiBaseUrl: 'http://localhost:8091' },-}))-vi.mock('../src/httpClient.js', () => ({+import { describe, it, expect, vi } from "vitest";++vi.mock("../src/config.js", () => ({+ config: { requestTimeoutMs: 5000, externalRestApiBaseUrl: "http://localhost:8091" },+}));+vi.mock("../src/httpClient.js", () => ({requestJson: vi.fn(),- ApiError: class extends Error {- status = 0- bodyText = ''- },-}))+ ApiError: class extends Error { status = 0; bodyText = ""; },+}));++import { RpcTokenManager } from "../src/rpcTokenManager.js";+import type { AuthClient } from "../src/authClient.js";// ── Helpers ───────────────────────────────────────────────────────────────────-function makeAuthClient(token = 'rpc-token-123', expiresInSeconds = 60) {+function makeAuthClient(token = "rpc-token-123", expiresInSeconds = 60) {return {issueRpcToken: vi.fn().mockResolvedValue({token,- teamId: 'team-1',- scopes: ['host:message:invoke'],- hostRefs: ['chatllm'],+ teamId: "team-1",+ scopes: ["host:message:invoke"],+ hostRefs: ["chatllm"],expiresInSeconds,}),- } as unknown as AuthClient+ } as unknown as AuthClient;}// ── Tests ─────────────────────────────────────────────────────────────────────-describe('RpcTokenManager — initial state', () => {- it('returns null expiresAtMs before any token is fetched', () => {- const manager = new RpcTokenManager(makeAuthClient())- const meta = manager.getMetadata()+describe("RpcTokenManager — initial state", () => {+ it("returns null expiresAtMs before any token is fetched", () => {+ const manager = new RpcTokenManager(makeAuthClient());+ const meta = manager.getMetadata();- expect(meta.expiresAtMs).toBeNull()- expect(meta.scopes).toEqual([])- expect(meta.hostRefs).toEqual([])- })-})+ expect(meta.expiresAtMs).toBeNull();+ expect(meta.scopes).toEqual([]);+ expect(meta.hostRefs).toEqual([]);+ });+});-describe('RpcTokenManager — clear()', () => {- it('resets cache so next getOrIssue() fetches fresh', async () => {- const authClient = makeAuthClient()- const manager = new RpcTokenManager(authClient)+describe("RpcTokenManager — clear()", () => {+ it("resets cache so next getOrIssue() fetches fresh", async () => {+ const authClient = makeAuthClient();+ const manager = new RpcTokenManager(authClient);// Prime cache- await manager.getOrIssue('sess-token', ['host:message:invoke'])- expect(authClient.issueRpcToken).toHaveBeenCalledOnce()+ await manager.getOrIssue("sess-token", ["host:message:invoke"]);+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();// After clear(), a second getOrIssue() should re-fetch- manager.clear()- await manager.getOrIssue('sess-token', ['host:message:invoke'])- expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2)- })-})--describe('RpcTokenManager — getOrIssue()', () => {- it('fetches a new token when cache is empty', async () => {- const authClient = makeAuthClient('rpc-fresh-token')- const manager = new RpcTokenManager(authClient)-- const result = await manager.getOrIssue('sess-token', ['host:message:invoke'])- expect(result.token).toBe('rpc-fresh-token')- expect(authClient.issueRpcToken).toHaveBeenCalledOnce()- })-- it('reuses cached token on second call when not expired', async () => {- const authClient = makeAuthClient('rpc-cached-token', 60)- const manager = new RpcTokenManager(authClient)-- const first = await manager.getOrIssue('sess-token', ['host:message:invoke'])- const second = await manager.getOrIssue('sess-token', ['host:message:invoke'])-- expect(first.token).toBe(second.token)+ manager.clear();+ await manager.getOrIssue("sess-token", ["host:message:invoke"]);+ expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2);+ });+});++describe("RpcTokenManager — getOrIssue()", () => {+ it("fetches a new token when cache is empty", async () => {+ const authClient = makeAuthClient("rpc-fresh-token");+ const manager = new RpcTokenManager(authClient);++ const result = await manager.getOrIssue("sess-token", ["host:message:invoke"]);+ expect(result.token).toBe("rpc-fresh-token");+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();+ });++ it("reuses cached token on second call when not expired", async () => {+ const authClient = makeAuthClient("rpc-cached-token", 60);+ const manager = new RpcTokenManager(authClient);++ const first = await manager.getOrIssue("sess-token", ["host:message:invoke"]);+ const second = await manager.getOrIssue("sess-token", ["host:message:invoke"]);++ expect(first.token).toBe(second.token);// Should only have fetched once (cache hit)- expect(authClient.issueRpcToken).toHaveBeenCalledOnce()- })+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();+ });- it('re-fetches when token is expired (expiresInSeconds = 0)', async () => {- const authClient = makeAuthClient('rpc-expired', 0)- const manager = new RpcTokenManager(authClient)+ it("re-fetches when token is expired (expiresInSeconds = 0)", async () => {+ const authClient = makeAuthClient("rpc-expired", 0);+ const manager = new RpcTokenManager(authClient);// First call populates cache with 0s TTL (expired immediately)- await manager.getOrIssue('sess-token', ['host:message:invoke'])+ await manager.getOrIssue("sess-token", ["host:message:invoke"]);// Override to return fresh tokenvi.mocked(authClient.issueRpcToken).mockResolvedValueOnce({- token: 'rpc-fresh-2',- accessScope: 'team',- teamId: 'team-1',- scopes: ['host:message:invoke'],- hostRefs: ['chatllm'],+ token: "rpc-fresh-2",+ accessScope: "team",+ teamId: "team-1",+ scopes: ["host:message:invoke"],+ hostRefs: ["chatllm"],expiresInSeconds: 60,- })+ });- const result = await manager.getOrIssue('sess-token', ['host:message:invoke'])- expect(result.token).toBe('rpc-fresh-2')- expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2)- })+ const result = await manager.getOrIssue("sess-token", ["host:message:invoke"]);+ expect(result.token).toBe("rpc-fresh-2");+ expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2);+ });- it('returns metadata reflecting cached token after first fetch', async () => {- const manager = new RpcTokenManager(makeAuthClient('tok', 120))- await manager.getOrIssue('sess', ['host:message:invoke'])+ it("returns metadata reflecting cached token after first fetch", async () => {+ const manager = new RpcTokenManager(makeAuthClient("tok", 120));+ await manager.getOrIssue("sess", ["host:message:invoke"]);- const meta = manager.getMetadata()- expect(meta.expiresAtMs).toBeGreaterThan(Date.now())- expect(meta.scopes).toContain('host:message:invoke')- expect(meta.hostRefs).toContain('chatllm')- })-})+ const meta = manager.getMetadata();+ expect(meta.expiresAtMs).toBeGreaterThan(Date.now());+ expect(meta.scopes).toContain("host:message:invoke");+ expect(meta.hostRefs).toContain("chatllm");+ });+});// ── Subset-scope reuse: INTENTIONAL, pinned on purpose ────────────────────────//@@ -125,35 +123,35 @@ describe('RpcTokenManager — getOrIssue()', () => {// undocumented side effect: if someone later makes stream open a wake-capable// route, or narrows this cache to exact-scope keying, one of these two// assertions turns red and forces the decision to be made explicitly.-describe('RpcTokenManager — subset scope reuse', () => {- it('serves a narrower request from the cached superset token, which still carries host:wake:write', async () => {+describe("RpcTokenManager — subset scope reuse", () => {+ it("serves a narrower request from the cached superset token, which still carries host:wake:write", async () => {const authClient = {issueRpcToken: vi.fn().mockResolvedValue({- token: 'rpc-token-superset',- accessScope: 'team',- teamId: 'team-1',- scopes: ['host:activity:read', 'host:task:read', 'host:wake:write'],- hostRefs: ['chatllm'],+ token: "rpc-token-superset",+ accessScope: "team",+ teamId: "team-1",+ scopes: ["host:activity:read", "host:task:read", "host:wake:write"],+ hostRefs: ["chatllm"],expiresInSeconds: 60,}),- } as unknown as AuthClient- const manager = new RpcTokenManager(authClient)+ } as unknown as AuthClient;+ const manager = new RpcTokenManager(authClient);// Broad issuance (e.g. a finite operation that legitimately needs wake).await manager.getOrIssue(- 'sess-token',- ['host:activity:read', 'host:task:read', 'host:wake:write'],- ['chatllm']- )- expect(authClient.issueRpcToken).toHaveBeenCalledOnce()+ "sess-token",+ ["host:activity:read", "host:task:read", "host:wake:write"],+ ["chatllm"]+ );+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();// Narrower request (e.g. an observability read) — served from cache.- const reused = await manager.getOrIssue('sess-token', ['host:activity:read'], ['chatllm'])+ const reused = await manager.getOrIssue("sess-token", ["host:activity:read"], ["chatllm"]);// 1. Exactly ONE issuance: the subset did not trigger a second round trip.- expect(authClient.issueRpcToken).toHaveBeenCalledOnce()+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();// 2. The DELIVERED token is the cached superset — it still carries wake.- expect(reused.token).toBe('rpc-token-superset')- expect(reused.scopes).toContain('host:wake:write')- })-})+ expect(reused.token).toBe("rpc-token-superset");+ expect(reused.scopes).toContain("host:wake:write");+ });+});diff --git a/desktop-app/ui/src/gfs/GfsGrantList/types.ts b/desktop-app/ui/src/gfs/GfsGrantList/types.tsindex 727e5faab..18bc9cd87 100644--- a/desktop-app/ui/src/gfs/GfsGrantList/types.ts+++ b/desktop-app/ui/src/gfs/GfsGrantList/types.ts@@ -1,9 +1,9 @@-import type { GfsGrantErrorPresentation } from '@lib/gfsGrantErrors'import type {GfsAgentSubjectOption,GfsDelegationSubjectOption,GfsGrantListItem,} from '@/gfs/delegation.types'+import type { GfsGrantErrorPresentation } from '@lib/gfsGrantErrors'export interface GfsGrantListProps {items: GfsGrantListItem[]diff --git a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsxindex 3744df990..172f82176 100644--- a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx@@ -19,7 +19,9 @@ const agents = [describe('GfsAgentAccessSection', () => {it('offers ONLY read and write permissions for agents', () => {- render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={vi.fn()} />)+ render(+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={vi.fn()} />+ )fireEvent.click(screen.getByRole('button', { name: 'Read' }))expect(screen.getByRole('menuitemcheckbox', { name: 'Read' })).toBeTruthy()@@ -31,7 +33,9 @@ describe('GfsAgentAccessSection', () => {it('emits host:-prefixed subject keys for the selected agents', async () => {const onGrantAgents = vi.fn().mockResolvedValue(undefined)- render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />)+ render(+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />+ )fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))fireEvent.click(screen.getByRole('button', { name: 'chatllm-stateless' }))@@ -48,7 +52,9 @@ describe('GfsAgentAccessSection', () => {it('defaults the inherit toggle ON for directories and honors turning it off', async () => {const onGrantAgents = vi.fn().mockResolvedValue(undefined)- render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />)+ render(+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />+ )const inherit = screen.getByRole('checkbox', { name: 'Include contents of this folder' })expect(inherit).toHaveProperty('checked', true)@@ -68,7 +74,9 @@ describe('GfsAgentAccessSection', () => {<GfsAgentAccessSection agents={agents} isDirectory={false} onGrantAgents={onGrantAgents} />)- expect(screen.queryByRole('checkbox', { name: 'Include contents of this folder' })).toBeNull()+ expect(+ screen.queryByRole('checkbox', { name: 'Include contents of this folder' })+ ).toBeNull()fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))@@ -84,7 +92,9 @@ describe('GfsAgentAccessSection', () => {const onGrantAgents = vi.fn().mockRejectedValue(new Error('403 Forbidden: managed_agent_permission_forbidden'))- render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />)+ render(+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />+ )fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))fireEvent.click(screen.getByRole('button', { name: 'chatllm-stateless' }))@@ -98,9 +108,9 @@ describe('GfsAgentAccessSection', () => {true)// SelectableOption only sets aria-pressed="true" while selected — both stay.- expect(screen.getByRole('button', { name: 'chatllm' }).getAttribute('aria-pressed')).toBe(- 'true'- )+ expect(+ screen.getByRole('button', { name: 'chatllm' }).getAttribute('aria-pressed')+ ).toBe('true')expect(screen.getByRole('button', { name: 'chatllm-stateless' }).getAttribute('aria-pressed')).toBe('true')diff --git a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsxindex e9989c5a5..ed69207c4 100644--- a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx@@ -1,8 +1,8 @@// @vitest-environment jsdomimport { afterEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'-import { GfsGrantList } from '../GfsGrantList'import type { GfsGrantListItem } from '../delegation.types'+import { GfsGrantList } from '../GfsGrantList'/*** "Who has access" list (Manage modal). Rows resolve host subjects to agent@@ -88,7 +88,9 @@ describe('GfsGrantList', () => {/>)- const banner = screen.getByText('Only people with manage access can view who has access here.')+ const banner = screen.getByText(+ 'Only people with manage access can view who has access here.'+ )expect(banner.closest('.status-banner')?.className).toContain('tone-info')expect(screen.queryByRole('list')).toBeNull()expect(screen.queryByRole('button', { name: /Revoke access for/ })).toBeNull()diff --git a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.tsindex 1a3407e3f..f2df6c2e8 100644--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts@@ -14,8 +14,14 @@ import { describeGfsGrantError } from '../gfsGrantErrors'describe('describeGfsGrantError', () => {it.each([- ['agent_manager_forbidden', "Agents can't be given manage or share access."],- ['managed_agent_permission_forbidden', 'Managed agents can only be granted read and write.'],+ [+ 'agent_manager_forbidden',+ "Agents can't be given manage or share access.",+ ],+ [+ 'managed_agent_permission_forbidden',+ 'Managed agents can only be granted read and write.',+ ],['foreign_agent_forbidden', 'You can only grant access to your own agents.'],['escalation_rejected', 'You can only grant permissions you already hold here.'],])('maps %s to its human message with error severity', (code, message) => {@@ -28,9 +34,7 @@ describe('describeGfsGrantError', () => {it('maps manage_acl_required to a quiet banner, never an error toast', () => {const presentation = describeGfsGrantError(- new Error(- "Error invoking remote method 'gfs:listGrants': Error: 403 Forbidden: manage_acl_required"- )+ new Error("Error invoking remote method 'gfs:listGrants': Error: 403 Forbidden: manage_acl_required"))expect(presentation).toEqual({diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex 8c9ed6df9..8e75585ae 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -19,13 +19,13 @@ import { describeGfsGrantError } from '@lib/gfsGrantErrors'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'import { formatSharedFileSize } from '@lib/sharedFiles'-import { GfsAgentAccessSection } from '@/gfs/GfsAgentAccessSection'-import { GfsGrantList } from '@/gfs/GfsGrantList'import {- type GfsAgentSubjectOption,GfsDelegationPanel,+ type GfsAgentSubjectOption,type GfsDelegationSubjectOption,} from '@/gfs/delegation'+import { GfsAgentAccessSection } from '@/gfs/GfsAgentAccessSection'+import { GfsGrantList } from '@/gfs/GfsGrantList'import { GfsFilePicker } from '@/gfs/filePicker'import { normalizeGfsResourceName } from '@/gfs/resourceName'import type { TeamDirectoryResult } from '../../../src/types'@@ -158,7 +158,10 @@ export function FilesPage({ pushToast }: FilesPageProps) {queryFn: () => window.clerum.agents.listMine(),enabled: manageOpen,})- const agentSubjects = useMemo(() => agentSubjectOptions(myAgentsQuery.data), [myAgentsQuery.data])+ const agentSubjects = useMemo(+ () => agentSubjectOptions(myAgentsQuery.data),+ [myAgentsQuery.data]+ )const grantsError = useMemo(() => (ctrl.grantsError ? describeGfsGrantError(ctrl.grantsError) : null),[ctrl.grantsError]@@ -1006,9 +1009,7 @@ export function FilesPage({ pushToast }: FilesPageProps) {<div className="da-gfs-manage-section__header"><div><h4>Who has access</h4>- <p className="muted">- Existing grants on this resource. Revoking is immediate.- </p>+ <p className="muted">Existing grants on this resource. Revoking is immediate.</p></div></div><GfsGrantListdiff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 587080184..5ef32fb7d 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -954,7 +954,10 @@ describe('FilesPage', () => {// The panel maps the verdict; no partial-success toast, no list-after-write.await screen.findByText('Some selected subjects are invalid and were rejected.')expect(refreshGrants).not.toHaveBeenCalled()- expect(pushToast).not.toHaveBeenCalledWith(expect.stringContaining('Access granted'), 'success')+ expect(pushToast).not.toHaveBeenCalledWith(+ expect.stringContaining('Access granted'),+ 'success'+ )})it('revokes a grant from the who-has-access list and toasts the outcome', async () => {diff --git a/host-context-controller/src/gfsConfig.ts b/host-context-controller/src/gfsConfig.tsindex 331e43599..1c8760c14 100644--- a/host-context-controller/src/gfsConfig.ts+++ b/host-context-controller/src/gfsConfig.ts@@ -60,7 +60,10 @@ export function gfsDefaultFactoryConfig(): GfsFactoryConfig {jwtPublicKeyConfigMapKey: env('CONTEXT_MAPPER_GFS_JWT_CONFIGMAP_KEY', 'jwt-public-key'),pgSecretName: env('CONTEXT_MAPPER_GFS_PG_SECRET', 'gfs-controller-db'),pgSecretKey: env('CONTEXT_MAPPER_GFS_PG_SECRET_KEY', 'connection-string'),- readerPgSecretName: env('CONTEXT_MAPPER_GFS_READER_PG_SECRET', 'gfs-controller-reader-db'),+ readerPgSecretName: env(+ 'CONTEXT_MAPPER_GFS_READER_PG_SECRET',+ 'gfs-controller-reader-db'+ ),readerPgSecretKey: env('CONTEXT_MAPPER_GFS_READER_PG_SECRET_KEY', 'connection-string'),driveName: env('CONTEXT_MAPPER_GFS_DRIVE_NAME', 'main'),tokenAudience: env('CONTEXT_MAPPER_GFS_TOKEN_AUDIENCE', 'gfs-controller'),diff --git a/host-context-controller/src/gfsHostSubject.test.ts b/host-context-controller/src/gfsHostSubject.test.tsindex 68d1bfb09..6de4b5e9a 100644--- a/host-context-controller/src/gfsHostSubject.test.ts+++ b/host-context-controller/src/gfsHostSubject.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'import path from 'node:path'+import { describe, expect, it } from 'vitest'import { makeExpectedHostGfsSubject } from './gfsHostSubject'type HostSubjectVector = {@@ -13,7 +13,10 @@ type HostSubjectVector = {}const vectors = JSON.parse(- readFileSync(path.join(__dirname, '../../tests/contracts/gfs-host-subject-vectors.json'), 'utf8')+ readFileSync(+ path.join(__dirname, '../../tests/contracts/gfs-host-subject-vectors.json'),+ 'utf8'+ )) as HostSubjectVector[]describe('makeExpectedHostGfsSubject', () => {diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.tsindex 495a4bc38..c6d258c89 100644--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@ -10,11 +10,7 @@ import {createMockNetworkingApi,createMockRbacApi,} from '../test/__fixtures__/testMocks'-import {- HostFleetReconcileError,- HostReconciler,- destructiveCleanupAllowed,-} from './hostReconciler'+import { HostFleetReconcileError, HostReconciler, destructiveCleanupAllowed } from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'import { registry } from './metrics'import { HostCRD } from './types'@@ -359,20 +355,14 @@ describe('HostReconciler fleet failure isolation', () => {metadata: {name: 'orphan-a',namespace: 'mcp-host',- labels: {- 'clerum.io/managed-by': 'host-context-controller',- 'clerum.io/host': 'orphan-a',- },+ labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'orphan-a' },},} as k8s.V1Deployment,{metadata: {name: 'orphan-b',namespace: 'mcp-host',- labels: {- 'clerum.io/managed-by': 'host-context-controller',- 'clerum.io/host': 'orphan-b',- },+ labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'orphan-b' },},} as k8s.V1Deployment,])@@ -427,12 +417,7 @@ describe('HostReconciler bounded fleet workers', () => {rbacApi: asRbacApi(createMockRbacApi()),})// Isolate reconcile concurrency from the cleanup phase.- vi.spyOn(- reconciler as unknown as {- collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>- },- 'collectHostCleanupFailures'- ).mockResolvedValue([])+ vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])let active = 0let maxActive = 0const gates: Array<() => void> = []@@ -465,12 +450,7 @@ describe('HostReconciler bounded fleet workers', () => {networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),})- vi.spyOn(- reconciler as unknown as {- collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>- },- 'collectHostCleanupFailures'- ).mockResolvedValue([])+ vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])let active = 0let maxActive = 0const gates = new Map<string, () => void>()diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 5bf92cfa6..c9251dece 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -21,13 +21,6 @@ import {} from './k8s/sharedFileSystemFactory'import { hccLogger } from './logger'import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'-import {- hostCleanupDeferredTotal,- hostDeleteCleanupTotal,- hostReconcileDurationSeconds,- hostReconcileInFlight,- hostReconcileQueueWaitSeconds,-} from './metrics'import {MCP_HOST_GFS_TOKEN_SECRET_KEY,MCP_HOST_RUNTIME_TOKEN_SECRET_ACCESS_KEY,@@ -59,6 +52,13 @@ import {preserveServiceAssignedFields,replaceWithConflictRetry,} from './utils'+import {+ hostCleanupDeferredTotal,+ hostDeleteCleanupTotal,+ hostReconcileDurationSeconds,+ hostReconcileInFlight,+ hostReconcileQueueWaitSeconds,+} from './metrics'export type { EffectiveHostLifecycle } from './statelessLifecycle.types'@@ -3978,8 +3978,7 @@ export class HostReconciler {if (!authorityValid()) {const current = this.hostWatchAuthority()- const reason =- !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'+ const reason = !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'hostCleanupDeferredTotal.inc({ reason })console.warn(`[HostReconciler] Deferring orphan cleanup: ${reason}`)return failures@@ -4139,10 +4138,7 @@ export class HostReconciler {try {const list = await this.coreApi.listNamespacedSecret({namespace: channelsNs,- labelSelector: [- `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- 'clerum.io/component=channel-reader',- ].join(','),+ labelSelector: [`${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`, 'clerum.io/component=channel-reader'].join(','),})for (const sec of list.items ?? []) {const labels = sec.metadata?.labels@@ -4271,6 +4267,7 @@ export class HostReconciler {})return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])}+}function canonicalStringify(obj: Record<string, unknown>): string {diff --git a/host-context-controller/src/k8s/gfsFactory.ts b/host-context-controller/src/k8s/gfsFactory.tsindex 81430d656..a93a21a21 100644--- a/host-context-controller/src/k8s/gfsFactory.ts+++ b/host-context-controller/src/k8s/gfsFactory.ts@@ -256,7 +256,8 @@ export function buildPvc(}function gfscEnv(config: GfsFactoryConfig, role: GfscRole): k8s.V1EnvVar[] {- const pgSecretName = role === 'writer' ? config.pgSecretName : config.readerPgSecretName+ const pgSecretName =+ role === 'writer' ? config.pgSecretName : config.readerPgSecretNameconst pgSecretKey = role === 'writer' ? config.pgSecretKey : config.readerPgSecretKeyconst copyEnvEntries: ReadonlyArray<readonly [string, string | undefined]> = [['GFS_SYNC_COPY_MAX_OBJECTS', config.syncCopyMaxObjects],diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 375a37333..c4f573f0e 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -2399,10 +2399,9 @@ describe('McpServerWatcher Host periodic resync serialization', () => {order.push(`watch:${host.name}:${host.generation}`)})await (watcher as any).startHostWatch('test-host-rv')- if (!hostWatchCallback)- throw new Error('Host watch callback was not installed')- // Cache already synced: the full pass blocks purely on the mocked- // fullReconcile and does not drive recovery, isolating admission behavior.+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ // Cache already synced: the full pass blocks purely on the mocked+ // fullReconcile and does not drive recovery, isolating admission behavior.;(watcher as any).hostCacheSynced = trueconst full = (watcher as any).requestHostFleetReconcile(@@ -2476,7 +2475,11 @@ describe('McpServerWatcher Host periodic resync serialization', () => {spec: { host: 'same-host' },})- expect(order).toEqual(['reconcile:same-host:1', 'reconcile:same-host:2', 'delete:same-host'])+ expect(order).toEqual([+ 'reconcile:same-host:1',+ 'reconcile:same-host:2',+ 'delete:same-host',+ ])expect((watcher as any).hosts.has('same-host')).toBe(false)watcher.stop()})@@ -2968,10 +2971,7 @@ describe('McpServerWatcher Host watch generation', () => {spec: { host: 'retry-host', lifecycle: { stateless: true } },})expect(reconcile).toHaveBeenCalledOnce()- expect(reconcile).toHaveBeenCalledWith(- expect.objectContaining({ uid: 'retry-host-uid' }),- 'urgent'- )+ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ uid: 'retry-host-uid' }), 'urgent')expect((watcher as any).hostWatchRetryTimers.size).toBe(1)expect((watcher as any).latestHostWatchEventRevisions.size).toBe(1)@@ -3230,7 +3230,11 @@ describe('McpServerWatcher Host watch generation', () => {expect(reconcileDelete).toHaveBeenCalledWith('gone-host', 'mcp-host', expect.anything()))// A Host still present in the fresh snapshot is never deleted.- expect(reconcileDelete).not.toHaveBeenCalledWith('live-host', 'mcp-host', expect.anything())+ expect(reconcileDelete).not.toHaveBeenCalledWith(+ 'live-host',+ 'mcp-host',+ expect.anything()+ )watcher.stop()})@@ -3318,12 +3322,7 @@ describe('McpServerWatcher Host watch generation', () => {it('suppresses a watch event whose identity (uid) differs from the cached Host (#827 item 2)', () => {const watcher = new McpServerWatcher()- ;(watcher as any).hosts.set('x', {- name: 'x',- namespace: 'mcp-host',- uid: 'uid-B',- generation: 3,- })+ ;(watcher as any).hosts.set('x', { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 });(watcher as any).latestHostWatchEventRevisions.set('x', 7)// A stale MODIFIED carrying the OLD identity must not act on the recreated one.expect(@@ -3381,7 +3380,10 @@ describe('McpServerWatcher Host watch generation', () => {new Map([['waker', 'u1']]) // NOT recreated (same uid))await vi.waitFor(() =>- expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'waker' }), 'urgent')+ expect(reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'waker' }),+ 'urgent'+ ))watcher.stop()})@@ -3403,15 +3405,7 @@ describe('McpServerWatcher Host watch generation', () => {spec: { host: 'steady' },});(watcher as any).enqueueRecoveredUrgentHosts(- [- {- name: 'steady',- namespace: 'mcp-host',- uid: 'u1',- generation: 4,- spec: { host: 'steady' },- },- ],+ [{ name: 'steady', namespace: 'mcp-host', uid: 'u1', generation: 4, spec: { host: 'steady' } }],new Set(['steady']),new Map([['steady', 4]]),new Map([['steady', 'u1']])diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex ea754b7b5..e850c29ae 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -19,10 +19,15 @@ import { GfsReconciler } from './gfsReconciler'import { ControlApiGfsSeedClient } from './gfsSeedClient'import {HostFleetReconcileError,- type HostReconcileSource,HostReconciler,+ type HostReconcileSource,type ResolvedSfsMount,} from './hostReconciler'+import {+ hostDeleteCleanupTotal,+ hostFleetRequestsTotal,+ hostWatchRecoverySeconds,+} from './metrics'import {type InfrastructureTelemetryReporter,createInfrastructureTelemetryReporter,@@ -30,7 +35,6 @@ import {import { K8sGfsApi } from './k8s/gfsK8sApi'import { makeHostK8sApiClient } from './k8s/hostK8sApiClient'import { pvcName as sfsPvcName } from './k8s/sharedFileSystemFactory'-import { hostDeleteCleanupTotal, hostFleetRequestsTotal, hostWatchRecoverySeconds } from './metrics'import { NetworkPolicyReconciler } from './networkPolicyReconciler'import { McpServerReconciler } from './reconciler'import { SharedFileSystemReconciler } from './sharedFileSystemReconciler'diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.tsindex 75b8cc5f0..4de90228e 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -47,7 +47,9 @@ function gauge(options: {* (15s), and wake (45s) budgets, plus longer diagnostic tails. Shared by every* HCC reconcile/recovery latency histogram.*/-const RECONCILE_LATENCY_BUCKETS = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 15, 45, 120] as const+const RECONCILE_LATENCY_BUCKETS = [+ 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 15, 45, 120,+] as const/** Idempotent Histogram helper mirroring counter()/gauge(). */function histogram(options: {diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.tsindex 4e6593024..6d9918a16 100644--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@ -439,8 +439,7 @@ describe('HostReconciler.publishSuspendBlockedReason', () => {lifecycle: {state: 'active',wakeHandledGeneration: 0,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',},},})@@ -453,8 +452,7 @@ describe('HostReconciler.publishSuspendBlockedReason', () => {freshHostRead({state: 'active',wakeHandledGeneration: 0,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',}))diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.tsindex d624bf4e2..3bd808b44 100644--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts@@ -793,8 +793,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {expect(writes[1].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 5,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})expect(rejectedCondition(writes[1])).toMatchObject({status: 'True',@@ -873,8 +872,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {expect(writes[1].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 6,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})@@ -990,9 +988,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {)const writes = lifecycleStatusWrites(customApi)expect(writes).toHaveLength(2)- expect(writes[1].lifecycle?.reason).toBe(- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'- )+ expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle')})it('does not repeat bootstrap provisioning when channel ingress already existed in spec', async () => {@@ -1392,8 +1388,7 @@ describe('HostReconciler stateless lifecycle — kill-switches', () => {expect(writes[0].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 3,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})expect(rejectedCondition(writes[0]).status).toBe('True')})@@ -1607,8 +1602,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',expect(writes.at(-1)?.lifecycle).toEqual({state: 'active',wakeHandledGeneration: 3,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})@@ -1636,8 +1630,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',expect(writes.at(-1)?.lifecycle).toEqual({state: 'active',wakeHandledGeneration: 2,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})@@ -1663,8 +1656,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',expect(writes.at(-1)?.lifecycle).toEqual({state: 'suspended',wakeHandledGeneration: 5,- reason:- '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.tsindex ccb55d3a8..d250cf53e 100644--- a/host-context-controller/test/hostReconciler.test.ts+++ b/host-context-controller/test/hostReconciler.test.ts@@ -1,13 +1,13 @@import { describe, expect, it, vi } from 'vitest'import * as k8s from '@kubernetes/client-node'import type { AdministrativeOutcomeReporter } from '../src/administrativeOutcomeReporter'-import { mintHostGfsToken } from '../src/gfsHostBinding'import {DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES,HostReconciler,resolveWorkflowControlScopes,} from '../src/hostReconciler'import type { InfrastructureTelemetryReporter } from '../src/infrastructureTelemetryReporter'+import { mintHostGfsToken } from '../src/gfsHostBinding'import { issueMcpHostRuntimeTokens } from '../src/mcpHostRuntimeTokenIssuerClient'import { HostCRD, type HostWorkflowControlScope } from '../src/types'import {diff --git a/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts b/host-context-controller/test/statelessDeployment.workspaceLayout.test.tsindex 7b75c2327..790d3833b 100644--- a/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts+++ b/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts@@ -67,7 +67,8 @@ describe('stateless workspace layout migration', () => {expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('workspace-data')expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')- }, // runner budget above the generic 5s limit so CI process contention cannot // This is the only case that launches the migration shell twice. Keep its+ }, // This is the only case that launches the migration shell twice. Keep its+ // runner budget above the generic 5s limit so CI process contention cannot// turn a completed idempotency check into a harness timeout.15_000)diff --git a/mcp-host/src/internalTools/gfs.test.ts b/mcp-host/src/internalTools/gfs.test.tsindex ed2b8d154..ab15d5eff 100644--- a/mcp-host/src/internalTools/gfs.test.ts+++ b/mcp-host/src/internalTools/gfs.test.ts@@ -158,8 +158,14 @@ describe('buildGfsWriteTools (P4)', () => {})it.each([- ['clerum__gfs_write', { drive: 'main', resourceId: 'abc', content: 'hi' }],- ['clerum__gfs_rename', { drive: 'main', resourceId: 'abc', newName: 'renamed.txt' }],+ [+ 'clerum__gfs_write',+ { drive: 'main', resourceId: 'abc', content: 'hi' },+ ],+ [+ 'clerum__gfs_rename',+ { drive: 'main', resourceId: 'abc', newName: 'renamed.txt' },+ ],['clerum__gfs_copy',{ drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination' },@@ -182,34 +188,26 @@ describe('buildGfsWriteTools (P4)', () => {it('passes create and rename payloads without exposing move fields', async () => {const c = writeClient()const tools = new Map(buildGfsWriteTools(c).map(tool => [tool.name, tool]))- await tools- .get('clerum__gfs_create_file')!- .execute(- { drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello' },- ''- )- await tools- .get('clerum__gfs_create_folder')!- .execute({ drive: 'main', parentResourceId: 'parent', name: 'docs' }, '')- await tools- .get('clerum__gfs_rename')!- .execute({ drive: 'main', resourceId: 'abc', newName: 'renamed.txt', ifMatch: 4 }, '')+ await tools.get('clerum__gfs_create_file')!.execute(+ { drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello' },+ ''+ )+ await tools.get('clerum__gfs_create_folder')!.execute(+ { drive: 'main', parentResourceId: 'parent', name: 'docs' },+ ''+ )+ await tools.get('clerum__gfs_rename')!.execute(+ { drive: 'main', resourceId: 'abc', newName: 'renamed.txt', ifMatch: 4 },+ ''+ )expect(c.createFile).toHaveBeenCalledWith({- drive: 'main',- parentResourceId: 'parent',- name: 'note.txt',- content: 'hello',+ drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello',})expect(c.createFolder).toHaveBeenCalledWith({- drive: 'main',- parentResourceId: 'parent',- name: 'docs',+ drive: 'main', parentResourceId: 'parent', name: 'docs',})expect(c.rename).toHaveBeenCalledWith({- drive: 'main',- resourceId: 'abc',- newName: 'renamed.txt',- ifMatch: 4,+ drive: 'main', resourceId: 'abc', newName: 'renamed.txt', ifMatch: 4,})expect(tools.has('clerum__gfs_move')).toBe(false)expect(tools.has('clerum__gfs_delete')).toBe(false)@@ -221,11 +219,8 @@ describe('buildGfsWriteTools (P4)', () => {expect(tool.description).toContain('The original remains at the source')expect(tool.description).toContain('never deletes it')const args = {- drive: 'main',- sourceResourceId: 'source',- destinationParentId: 'destination',- newName: 'source-copy',- ifMatch: 7,+ drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination',+ newName: 'source-copy', ifMatch: 7,}const result = await tool.execute(args, '')expect(result.success).toBe(true)@@ -237,9 +232,7 @@ describe('buildGfsWriteTools (P4)', () => {it('does not expose backend paths or keys in mutation failures', async () => {const c = writeClient({- copy: vi.fn(async () => {- throw new Error('failed at /mnt/gfs/private/blob-key')- }),+ copy: vi.fn(async () => { throw new Error('failed at /mnt/gfs/private/blob-key') }),})const result = await buildGfsCopyTools(c)[0]!.execute({ drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination', ifMatch: 7 },diff --git a/mcp-host/src/internalTools/gfsClient.test.ts b/mcp-host/src/internalTools/gfsClient.test.tsindex a575f6355..dbb3e561c 100644--- a/mcp-host/src/internalTools/gfsClient.test.ts+++ b/mcp-host/src/internalTools/gfsClient.test.ts@@ -40,9 +40,8 @@ describe('gfs runtime gfsc client', () => {})it('derives only recognized GFS tool scopes and fails closed', () => {- expect([- ...(getGfsToolScopes({ get: () => encodedClaims(['gfs.read', 'gfs.write']) }) ?? []),- ]).toEqual(['gfs.read', 'gfs.write'])+ expect([...(getGfsToolScopes({ get: () => encodedClaims(['gfs.read', 'gfs.write']) }) ?? [])])+ .toEqual(['gfs.read', 'gfs.write'])expect(getGfsToolScopes({ get: () => encodedClaims(['gfs.read', 'gfs.delete']) })).toBeNull()expect(getGfsToolScopes({ get: () => encodedClaims(['gfs.delete']) })).toBeNull()expect(getGfsToolScopes({ get: () => encodedClaims([]) })).toBeNull()@@ -94,44 +93,35 @@ describe('gfs runtime gfsc client', () => {fetch: fetchFn,})await client.createFile({- drive: 'main',- parentResourceId: 'parent/id',- name: 'note.txt',- content: 'hello',+ drive: 'main', parentResourceId: 'parent/id', name: 'note.txt', content: 'hello',})await client.createFolder({ drive: 'main', parentResourceId: 'parent/id', name: 'docs' })await client.rename({- drive: 'main',- resourceId: 'source/id',- newName: 'renamed.txt',- ifMatch: 4,+ drive: 'main', resourceId: 'source/id', newName: 'renamed.txt', ifMatch: 4,})const copy = {- drive: 'main',- sourceResourceId: 'source',- destinationParentId: 'destination',- newName: 'source-copy',- ifMatch: 7,+ drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination',+ newName: 'source-copy', ifMatch: 7,}await client.copy(copy)expect(fetchFn.mock.calls.map(call => [call[0], call[1]?.method, call[1]?.body])).toEqual([['http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/parent%2Fid/children?drive=main',- 'POST',- JSON.stringify({ name: 'note.txt', kind: 'file', content: 'hello' }),+ 'POST', JSON.stringify({ name: 'note.txt', kind: 'file', content: 'hello' }),],['http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/parent%2Fid/children?drive=main',- 'POST',- JSON.stringify({ name: 'docs', kind: 'directory' }),+ 'POST', JSON.stringify({ name: 'docs', kind: 'directory' }),],['http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/source%2Fid',- 'PATCH',- JSON.stringify({ drive: 'main', newName: 'renamed.txt', ifMatch: 4 }),+ 'PATCH', JSON.stringify({ drive: 'main', newName: 'renamed.txt', ifMatch: 4 }),+ ],+ [+ 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/copy',+ 'POST', JSON.stringify(copy),],- ['http://gfsc-writer.gfs.svc.cluster.local:8087/v1/copy', 'POST', JSON.stringify(copy)],])})diff --git a/mcp-host/src/internalTools/gfsClient.ts b/mcp-host/src/internalTools/gfsClient.tsindex 115cc542f..f51305c40 100644--- a/mcp-host/src/internalTools/gfsClient.ts+++ b/mcp-host/src/internalTools/gfsClient.ts@@ -1,7 +1,7 @@import { existsSync, readFileSync } from 'node:fs'import { readFile } from 'node:fs/promises'-import { decodeRuntimeJwtScopes } from '../workflow/mcpHostRuntimeJwt'import type { GfscWriteClient } from './gfs'+import { decodeRuntimeJwtScopes } from '../workflow/mcpHostRuntimeJwt'const DIRECT_KEY = 'MCP_HOST_GFS_TOKEN'const FILE_KEY = 'MCP_HOST_GFS_TOKEN_FILE'diff --git a/mcp-host/src/workflow/mcpHostRuntimeJwt.ts b/mcp-host/src/workflow/mcpHostRuntimeJwt.tsindex e9b8902e6..65d9c84c9 100644--- a/mcp-host/src/workflow/mcpHostRuntimeJwt.ts+++ b/mcp-host/src/workflow/mcpHostRuntimeJwt.ts@@ -24,10 +24,7 @@ type RuntimeJwtClaims = {export function decodeRuntimeJwtScopes(token: string): string[] | null {try {const payload = decodeJwt(token) as RuntimeJwtClaims- if (- !Array.isArray(payload.scopes) ||- !payload.scopes.every(scope => typeof scope === 'string')- ) {+ if (!Array.isArray(payload.scopes) || !payload.scopes.every(scope => typeof scope === 'string')) {return null}return payload.scopesdiff --git a/rpc-proxy/src/__tests__/wake-route-coverage.test.ts b/rpc-proxy/src/__tests__/wake-route-coverage.test.tsindex b7289c749..eed0e33ba 100644--- a/rpc-proxy/src/__tests__/wake-route-coverage.test.ts+++ b/rpc-proxy/src/__tests__/wake-route-coverage.test.ts@@ -78,11 +78,7 @@ function makeApp() {return app}-function mockFetchResponse(- status: number,- body: string,- headers?: Record<string, string>-): Response {+function mockFetchResponse(status: number, body: string, headers?: Record<string, string>): Response {return {ok: status >= 200 && status < 300,status,@@ -107,10 +103,7 @@ const originalFetch = globalThis.fetchbeforeEach(() => {vi.clearAllMocks()serviceMock.resolveHostConnectionForUser.mockResolvedValue({ ...HOST_CONNECTION })- controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({- kind: 'active',- wakeGeneration: null,- })+ controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({ kind: 'active', wakeGeneration: null })})afterEach(() => {@@ -124,9 +117,7 @@ describe('§11.4 wake coverage — GET /rpc/hosts/:hostRef/models', () => {.fn().mockRejectedValueOnce(hostDownError()).mockResolvedValueOnce(- mockFetchResponse(200, JSON.stringify({ models: [] }), {- 'content-type': 'application/json',- })+ mockFetchResponse(200, JSON.stringify({ models: [] }), { 'content-type': 'application/json' }))globalThis.fetch = fetchMock as unknown as typeof fetch@@ -199,11 +190,13 @@ describe('§11.4 wake coverage — context-breakdown honors the draining fence',it('a plain upstream 404 is NOT treated as a wake trigger (passes through)', async () => {authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))- globalThis.fetch = vi.fn().mockResolvedValue(- mockFetchResponse(404, JSON.stringify({ error: 'session not found' }), {- 'content-type': 'application/json',- })- ) as unknown as typeof fetch+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(+ mockFetchResponse(404, JSON.stringify({ error: 'session not found' }), {+ 'content-type': 'application/json',+ })+ ) as unknown as typeof fetchconst res = await request(makeApp()).get('/rpc/hosts/chatllm/sessions/chatllm/missing/context-breakdown')@@ -334,7 +327,9 @@ describe('§11.4 wake coverage — approvals deny', () => {// wake-capable token never touches the wake plane when the host is up.describe('§13.4 row 3 — task result forwards normally on an active host', () => {it('an active host forwards the task result and never touches the wake plane', async () => {- authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke', 'host:wake:write']))+ authTokenMock.verifyRpcToken.mockReturnValue(+ claims(['host:message:invoke', 'host:wake:write'])+ )serviceMock.forwardTaskResultFromHost.mockResolvedValue({status: 'completed',response: 'done',diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex 5722441db..e06ad0f9a 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -1,5 +1,5 @@import { Router } from 'express'-import type { Response as ExpressResponse, NextFunction } from 'express'+import type { NextFunction, Response as ExpressResponse } from 'express'import { randomUUID } from 'crypto'import { config } from '../config.js'import {diff --git a/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts b/rpc-proxy/src/services/__tests__/probeHostHealth.test.tsindex 7efd0f186..07b34521b 100644--- a/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts+++ b/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts@@ -1,7 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ResolvedServerConnection } from '../../types.js'-// vi.mock is hoisted above imports, so the static import resolves the mock.-import { probeHostReadyViaHealth } from '../wakeAndHold.js'// The wake-and-hold readiness probe must use mcp-host's UNAUTHENTICATED// /v1/runtime/health endpoint (Issue #791 §11.3), which comes up before MCP@@ -15,6 +13,9 @@ const restMock = vi.hoisted(() => ({vi.mock('../mcpHostRestService.js', () => restMock)+// vi.mock is hoisted above imports, so the static import resolves the mock.+import { probeHostReadyViaHealth } from '../wakeAndHold.js'+const HOST: ResolvedServerConnection = {name: 'chatllm',url: 'http://chatllm.mcp-host.svc.cluster.local:8080',diff --git a/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts b/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.tsindex 03329a2be..3ad2db1d7 100644--- a/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts+++ b/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts@@ -91,11 +91,7 @@ afterEach(() => {describe('wakeCoordinationKey', () => {it('excludes jti/exp/role/scopes and is stable across token rotation for one principal', () => {const a = makeClaims({ jti: 'j1', expMs: Date.now() + 1_000_000, scopes: ['host:wake:write'] })- const b = makeClaims({- jti: 'j2',- expMs: Date.now() + 9_000_000,- scopes: ['host:session:read'],- })+ const b = makeClaims({ jti: 'j2', expMs: Date.now() + 9_000_000, scopes: ['host:session:read'] })expect(wakeCoordinationKey(a, 'chatllm')).toBe(wakeCoordinationKey(b, 'chatllm'))})diff --git a/rpc-proxy/src/services/wakeAndHold.ts b/rpc-proxy/src/services/wakeAndHold.tsindex a8b769594..a60c3a9d1 100644--- a/rpc-proxy/src/services/wakeAndHold.ts+++ b/rpc-proxy/src/services/wakeAndHold.ts@@ -217,12 +217,7 @@ export class WakeAndHoldCoordinator {const activeEntry = entryreturn await new Promise<WakeHoldOutcome>(resolve => {const id = ++this.waiterSeq- const waiter: Waiter = {- id,- resolve,- timer: null as unknown as NodeJS.Timeout,- settled: false,- }+ const waiter: Waiter = { id, resolve, timer: null as unknown as NodeJS.Timeout, settled: false }waiter.timer = setTimeout(() => {if (waiter.settled) returnwaiter.settled = truediff --git a/tests/e2e/gfsCopyFixtures.ts b/tests/e2e/gfsCopyFixtures.tsindex f139373cb..5b50b1c8d 100644--- a/tests/e2e/gfsCopyFixtures.ts+++ b/tests/e2e/gfsCopyFixtures.ts@@ -51,8 +51,7 @@ export function cleanupGfsCopyTreeFixture(fixture: GfsCopyTreeFixture): void {failures.push(`${name}: ${error instanceof Error ? error.message : String(error)}`)}}- if (failures.length > 0)- throw new Error(`GFS Copy fixture cleanup failed: ${failures.join('; ')}`)+ if (failures.length > 0) throw new Error(`GFS Copy fixture cleanup failed: ${failures.join('; ')}`)}function driveRoot(): string {@@ -299,18 +298,13 @@ export function getGfsHostGrantsUnderTree(rootId: string, subjectId: string): GfSELECT resource_id::text || '|' || array_to_string(permissions, ',') || '|' || inherit::textFROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM tree)AND subject_type = 'host' AND subject_id = ${sqlLiteral(subjectId)} ORDER BY resource_id;- `)- .split('\n')- .map(line => line.trim())- .filter(Boolean)- .map(row => {- const parts = splitSqlRow(row)- if (parts.length !== 3 || !UUID_RE.test(parts[0] ?? ''))- throw new Error(`invalid host grant row: ${row}`)- return {- resourceId: parts[0]!,- permissions: parts[1] ? parts[1].split(',') : [],- inherit: parts[2] === 't' || parts[2] === 'true',- }- })+ `).split('\n').map(line => line.trim()).filter(Boolean).map(row => {+ const parts = splitSqlRow(row)+ if (parts.length !== 3 || !UUID_RE.test(parts[0] ?? '')) throw new Error(`invalid host grant row: ${row}`)+ return {+ resourceId: parts[0]!,+ permissions: parts[1] ? parts[1].split(',') : [],+ inherit: parts[2] === 't' || parts[2] === 'true',+ }+ })}diff --git a/tests/e2e/gfsResourceFixtures.ts b/tests/e2e/gfsResourceFixtures.tsindex 6f97f4832..05d6d71de 100644--- a/tests/e2e/gfsResourceFixtures.ts+++ b/tests/e2e/gfsResourceFixtures.ts@@ -50,7 +50,10 @@ function cleanupGfsBlob(resourceId: string, blobKey?: string | null): void {return `/data/gfs/.generations/${blobKey}`})(): `/data/gfs/${ridOf(resourceId)}`- kubectlOut(['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', physicalPath], 20_000)+ kubectlOut(+ ['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', physicalPath],+ 20_000+ )}export function seedGfsDirectoryFixture(name: string): GfsDirectoryFixture {@@ -192,8 +195,7 @@ export function seedGfsGrant(input: {throw new Error(`subjectId is required for ${input.subjectType} GFS grants`)}const permissions = `ARRAY[${input.permissions.map(sqlLiteral).join(', ')}]::text[]`- const grantId = firstDataLine(- runControlPostgresSql(`+ const grantId = firstDataLine(runControlPostgresSql(`INSERT INTO gfs_grants (drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by)@@ -213,8 +215,7 @@ export function seedGfsGrant(input: {granted_by = EXCLUDED.granted_by,updated_at = now()RETURNING id::text;- `)- )+ `))if (!UUID_RE.test(grantId)) throw new Error(`failed to seed GFS grant: ${grantId}`)return grantId}@@ -346,8 +347,8 @@ export function cleanupGfsFixture(name: string): void {.map(line => line.trim()).filter(Boolean).map(splitSqlRow)- .filter(- (parts): parts is [string, string] => parts.length === 2 && UUID_RE.test(parts[0] ?? '')+ .filter((parts): parts is [string, string] =>+ parts.length === 2 && UUID_RE.test(parts[0] ?? ''))const cleanupErrors: unknown[] = []for (const [resourceId, blobKey] of resources) {