Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge remote-tracking branch 'origin/dev' into feat/ux-improvements-25
Miguelon Peluchon6c51d41ad1a9
diff --cc control-api/src/gfs/legacyStandaloneGrantMigration.tsindex 000000000,05e3fcd4c..5f423ac27mode 000000,100644..100644--- a/control-api/src/gfs/legacyStandaloneGrantMigration.ts+++ b/control-api/src/gfs/legacyStandaloneGrantMigration.ts@@@ -1,0 -1,233 +1,240 @@@+ export const LEGACY_STANDALONE_SUBJECT_KEY = 'host:1st:mcp-host/standalone'++ export interface LegacyGrantMigrationApi {+ getLegacyGrants(): Promise<unknown>+ getTrustedHostDirectory(): Promise<unknown>+ putGrant(body: Record<string, unknown>): Promise<{ ok: boolean; status?: number; error?: string }>+ }++ export interface LegacyGrantInventoryItem {+ id: string+ drive: string+ resourceId: string+ permissions: string[]+ inherit: boolean+ }++ export interface TrustedHostCandidate {+ name: string+ namespace: string+ displayName: string+ active: true+ gfsSubject: { type: 'host'; id: string }+ }++ const K8S_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i+ const MAX_INVENTORY_ITEMS = 1000+ const MAX_TARGETS_PER_SOURCE = 100+ const MIGRATABLE_MANAGED_AGENT_PERMISSIONS = new Set(['read', 'write'])++ function isK8sName(value: unknown): value is string {+ return typeof value === 'string' && value.length <= 63 && K8S_NAME_RE.test(value)+ }++ function normalizeCandidate(value: unknown): TrustedHostCandidate | null {+ if (!value || typeof value !== 'object') return null+ const item = value as Record<string, unknown>+ if (item.active !== true || !isK8sName(item.name) || !isK8sName(item.namespace)) return null+ const subject = item.gfsSubject as Record<string, unknown> | undefined+ const expectedId = `1st:${item.namespace}/${item.name}`+ const displayName = typeof item.displayName === 'string' ? item.displayName : item.name+ if (subject?.type !== 'host' || subject.id !== expectedId) return null+ if (`host:${expectedId}` === LEGACY_STANDALONE_SUBJECT_KEY) return null+ if (/^all([ -]clerum)?[ -]agents$/i.test(displayName.trim())) return null+ if (item.hidden === true || item.deleted === true || item.status === 'deleted') return null+ return {+ name: item.name,+ namespace: item.namespace,+ displayName,+ active: true,+ gfsSubject: { type: 'host', id: expectedId },+ }+ }++ function normalizeGrant(value: unknown): LegacyGrantInventoryItem {+ if (!value || typeof value !== 'object') throw new Error('legacy_grant_report_invalid')+ const item = value as Record<string, unknown>+ if (!UUID_RE.test(String(item.id ?? '')) || !UUID_RE.test(String(item.resourceId ?? ''))) {+ throw new Error('legacy_grant_report_invalid')+ }+ if (typeof item.drive !== 'string' || !Array.isArray(item.permissions)) {+ throw new Error('legacy_grant_report_invalid')+ }+ if (item.permissions.some(permission => typeof permission !== 'string')) {+ throw new Error('legacy_grant_report_invalid')+ }+ if (+ item.permissions.length === 0 ||+ item.permissions.some(permission => !MIGRATABLE_MANAGED_AGENT_PERMISSIONS.has(permission))+ ) {+ // Never silently reduce or reproduce historical authority. An operator+ // must review and replace a legacy grant containing forbidden bits before+ // it can be migrated to individual HCC-managed agents.+ throw new Error('legacy_grant_permissions_forbidden')+ }+ return {+ id: String(item.id),+ drive: item.drive,+ resourceId: String(item.resourceId),+ permissions: [...new Set(item.permissions as string[])].sort(),+ inherit: item.inherit === true,+ }+ }++ 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)+ }++ export function sameReviewedInventory(left: unknown, right: unknown): boolean {+ return canonicalJson(left) === canonicalJson(right)+ }++ export async function buildLegacyGrantMigrationReport(api: LegacyGrantMigrationApi) {+ const [legacyValue, directoryValue] = await Promise.all([+ api.getLegacyGrants(),+ api.getTrustedHostDirectory(),+ ])+ const legacy = legacyValue as { sourceSubject?: unknown; grants?: unknown }+ const directory = directoryValue as { agents?: unknown }+ if (legacy?.sourceSubject !== LEGACY_STANDALONE_SUBJECT_KEY || !Array.isArray(legacy.grants)) {+ throw new Error('legacy_grant_report_invalid')+ }+ if (!Array.isArray(directory?.agents)) throw new Error('trusted_host_directory_invalid')+ if (legacy.grants.length > MAX_INVENTORY_ITEMS || directory.agents.length > MAX_INVENTORY_ITEMS) {+ throw 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)+ .sort((a, b) => a.gfsSubject.id.localeCompare(b.gfsSubject.id))+ if (+ new Set(validIndividualHostCandidates.map(candidate => candidate.gfsSubject.id)).size !==+ validIndividualHostCandidates.length+ ) {+ throw new Error('trusted_host_directory_duplicate')+ }+ return {+ mode: 'report' as const,+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,+ sourceGrants,+ validIndividualHostCandidates,+ mappingTemplate: {+ version: 1,+ reviewedSourceGrants: sourceGrants,+ reviewedHostCandidates: validIndividualHostCandidates,+ mappings: sourceGrants.map(grant => ({ sourceGrantId: grant.id, targets: [] as string[] })),+ },+ note: 'Candidate Hosts are inventory only; no assignment is inferred.',+ }+ }++ export function validateReviewedLegacyGrantMapping(+ report: Awaited<ReturnType<typeof buildLegacyGrantMigrationReport>>,+ mappingValue: unknown+ ): Map<string, string[]> {+ if (!mappingValue || typeof mappingValue !== 'object') throw new Error('mapping_invalid')+ const mapping = mappingValue as Record<string, unknown>+ if (mapping.version !== 1 || !Array.isArray(mapping.mappings)) throw new Error('mapping_invalid')+ 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))+ const candidates = new Set(+ report.validIndividualHostCandidates.map(candidate => `host:${candidate.gfsSubject.id}`)+ )+ const reviewed = new Map<string, string[]>()+ for (const value of mapping.mappings) {+ if (!value || typeof value !== 'object') throw new Error('mapping_invalid')+ const entry = value as Record<string, unknown>+ if (typeof entry.sourceGrantId !== 'string' || reviewed.has(entry.sourceGrantId)) {+ throw new Error('mapping_source_duplicate_or_invalid')+ }+ if (!grants.has(entry.sourceGrantId)) throw new Error('mapping_source_unknown')+ if (+ !Array.isArray(entry.targets) ||+ entry.targets.length === 0 ||+ entry.targets.length > MAX_TARGETS_PER_SOURCE+ ) {+ throw new Error('mapping_targets_required_or_excessive')+ }+ const targets = entry.targets.map(String)+ if (new Set(targets).size !== targets.length) throw new Error('mapping_target_duplicate')+ for (const target of targets) {+ if (+ target === LEGACY_STANDALONE_SUBJECT_KEY ||+ !target.startsWith('host:1st:') ||+ !candidates.has(target)+ ) {+ throw new Error('mapping_target_not_current_trusted_host')+ }+ }+ reviewed.set(entry.sourceGrantId, targets.sort())+ }+ if (reviewed.size !== grants.size) throw new Error('mapping_source_missing')+ return reviewed+ }++ export async function applyReviewedLegacyGrantMigration(+ api: LegacyGrantMigrationApi,+ mapping: unknown+ ) {+ // This fresh report is intentionally the final inventory read before any+ // mutation. The exact reviewed snapshots must still match current truth.+ const report = await buildLegacyGrantMigrationReport(api)+ const reviewed = validateReviewedLegacyGrantMapping(report, mapping)+ const sources = []+ for (const grant of report.sourceGrants) {+ const targets = []+ for (const target of reviewed.get(grant.id) ?? []) {+ const result = await api.putGrant({+ drive: grant.drive,+ resourceId: grant.resourceId,+ subject: { type: 'host', id: target.slice('host:'.length) },+ permissions: grant.permissions,+ inherit: grant.inherit,+ })+ targets.push({+ target,+ ok: result.ok,+ status: result.status ?? null,+ error: result.error ?? null,+ })+ }+ sources.push({+ sourceGrantId: grant.id,+ legacyGrantPreserved: true,+ readyForRetirement: targets.every(target => target.ok),+ targets,+ })+ }+ return {+ mode: 'apply' as const,+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,+ allApprovedIndividualGrantsSucceeded: sources.every(source => source.readyForRetirement),+ legacyGrantsDeleted: false,+ sources,+ }+ }diff --cc control-api/src/gfs/seedResources.tsindex 4aa4dde76,3ce31a88c..9458a5282--- a/control-api/src/gfs/seedResources.ts+++ b/control-api/src/gfs/seedResources.ts@@@ -87,6 -126,13 +126,12 @@@ export interface SeedDbexport 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: {drive: stringparentResourceId: string | null@@@ -125,8 -219,65 +218,67 @@@WHERE drive = $1 AND parent_resource_id = $2 AND name = $3 AND deleted_at IS NULL`,[drive, parentResourceId, name])- return resourceIdOf(existing.rows[0])+ const racedSibling = directoryRowOf(existing.rows[0])+ if (racedSibling.kind !== 'directory' || racedSibling.path_cache !== expectedPath) {+ throw new Error('[gfs] seed: concurrently inserted directory is not canonical')+ }+ return racedSibling.resource_id+ }++ private async loadDirectoryChain(resourceId: string): Promise<DirectoryChainRow[]> {+ const result = await this.db.query(+ `WITH RECURSIVE chain AS (+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.path_cache,+ r.deleted_at, ARRAY[r.resource_id]::uuid[] visited, false cycle+ FROM gfs_resources r WHERE r.resource_id = $1::uuid+ UNION ALL+ SELECT p.resource_id, p.drive, p.parent_resource_id, p.name, p.kind, p.path_cache,+ p.deleted_at, c.visited || p.resource_id, p.resource_id = ANY(c.visited)+ FROM chain c JOIN gfs_resources p ON p.resource_id = c.parent_resource_id+ WHERE NOT c.cycle+ ) SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, deleted_at, cycle+ FROM chain`,+ [resourceId]+ )+ return result.rows as DirectoryChainRow[]+ }+ }++ interface DirectoryChainRow {+ resource_id: string+ drive: string+ parent_resource_id: string | null+ name: string+ kind: string+ path_cache: string | null+ deleted_at: string | null+ cycle?: boolean+ }++ function directoryRowOf(row: unknown): DirectoryChainRow {+ const value = row as DirectoryChainRow | undefined+ if (!value || typeof value.resource_id !== 'string') {+ throw new Error('[gfs] seed: expected a resource_id row but got none')+ }+ return value+ }++ 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+ ) {+ throw new Error('[gfs] seed: parent ancestry is not a live same-drive directory chain')}+ const segments = rows+ .slice(0, -1)+ .map(row => row.name)+ .reverse()+ return segments.length === 0 ? '/' : `/${segments.join('/')}`}function resourceIdOf(row: unknown): string {diff --cc control-api/src/routes/admin/hostsOverview.tsindex f9e50f83f,cbf9f0990..efa531bd0--- a/control-api/src/routes/admin/hostsOverview.ts+++ b/control-api/src/routes/admin/hostsOverview.ts@@@ -3,6 -3,6 +3,7 @@@ import { config } from '../../config.jsimport { 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,diff --cc control-api/src/routes/external/gfs.tsindex 42305a782,1ba8cccde..d3a655351--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@@ -7,7 -7,8 +7,8 @@@ import} from '../../auth/gfsToken.js'import { config } from '../../config.js'import { pool } from '../../db.js'-import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'+ import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'+import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'import { asyncHandler } from '../../http/asyncHandler.js'import {type ExternalAuthedRequest,diff --cc control-api/src/routes/gfs/index.tsindex 8b2183501,bf88da8d7..b82c8b199--- a/control-api/src/routes/gfs/index.ts+++ b/control-api/src/routes/gfs/index.ts@@@ -1,5 -1,5 +1,6 @@@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'diff --cc control-api/src/routes/gfs/resources.tsindex b7211de41,5c2ee7ae9..012ad7fa4--- a/control-api/src/routes/gfs/resources.ts+++ b/control-api/src/routes/gfs/resources.ts@@@ -65,13 -56,10 +56,14 @@@ interface ResourceRowname: stringkind: stringversion: number+ 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(@@@ -82,11 -70,107 +74,113 @@@return (res.rows[0] as ResourceRow | undefined) ?? null}- /**- * Authorize and apply a rename/move. Pure of HTTP — throws ResourcePatchError- * with the spec error code; tests drive it with a fake GrantsDb. Returns the new- * version (etag).- */-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])+ }++ async function lockRows(db: GrantsDb, resourceIds: Iterable<string>): Promise<void> {+ const ids = [...new Set(resourceIds)].sort()+ if (ids.length === 0) return+ await db.query(+ `SELECT resource_id+ FROM gfs_resources+ WHERE resource_id = ANY($1::uuid[])+ ORDER BY resource_id+ FOR UPDATE`,+ [ids]+ )+ }++ async function loadAncestorChain(db: GrantsDb, resourceId: string): Promise<AncestorRow[]> {+ const result = await db.query(+ `WITH RECURSIVE chain AS (+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.version, r.deleted_at,+ ARRAY[r.resource_id]::uuid[] AS visited, false AS cycle+ FROM gfs_resources r WHERE r.resource_id = $1::uuid+ UNION ALL+ SELECT p.resource_id, p.drive, p.parent_resource_id, p.name, p.kind,+ p.version, p.deleted_at, c.visited || p.resource_id,+ p.resource_id = ANY(c.visited) AS cycle+ FROM chain c JOIN gfs_resources p ON p.resource_id = c.parent_resource_id WHERE NOT c.cycle+ )+ SELECT resource_id, drive, parent_resource_id, name, kind, version, deleted_at, cycle+ FROM chain`,+ [resourceId]+ )+ return result.rows as AncestorRow[]+ }++ function 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+ ) {+ throw new ResourcePatchError(412, 'precondition_failed')+ }+ }++ 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,+ resourceId: string,+ rootPath: string+ ): Promise<void> {+ const result = await db.query(+ `WITH RECURSIVE subtree AS (+ SELECT r.resource_id, $3::text canonical_path,+ ARRAY[r.resource_id]::uuid[] visited, false cycle FROM gfs_resources r+ WHERE r.resource_id = $2::uuid AND r.drive = $1 AND r.deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id,+ CASE WHEN parent.canonical_path = '/' THEN '/' || child.name+ ELSE parent.canonical_path || '/' || child.name END,+ parent.visited || child.resource_id, child.resource_id = ANY(parent.visited)+ FROM subtree parent JOIN gfs_resources child ON child.parent_resource_id = parent.resource_id+ AND child.drive = $1 AND child.deleted_at IS NULL WHERE NOT parent.cycle+ ),+ canonical AS (+ SELECT resource_id, canonical_path FROM subtree WHERE NOT cycle+ ),+ updated AS (+ UPDATE gfs_resources resource SET path_cache = canonical.canonical_path, updated_at = now()+ FROM canonical WHERE resource.resource_id = canonical.resource_id RETURNING resource.resource_id+ )+ SELECT (SELECT count(DISTINCT resource_id) FROM subtree WHERE NOT cycle) AS expected_count,+ (SELECT count(*) FROM updated) AS updated_count,+ (SELECT count(*) FROM canonical) AS canonical_count,+ (SELECT count(DISTINCT canonical_path) FROM canonical) AS distinct_path_count,+ EXISTS (SELECT 1 FROM subtree WHERE cycle) AS has_cycle`,+ [drive, resourceId, rootPath]+ )+ const row = result.rows[0] as Record<string, string | number | boolean> | undefined+ if (!row) throw new ResourcePatchError(412, 'precondition_failed')+ const expected = Number(row.expected_count)+ if (+ row.has_cycle ||+ expected === 0 ||+ Number(row.updated_count) !== expected ||+ Number(row.canonical_count) !== expected ||+ Number(row.distinct_path_count) !== expected+ ) {+ throw new ResourcePatchError(412, 'precondition_failed')+ }+ }+export async function applyResourcePatch(db: GrantsDb,caller: GfsCaller,@@@ -122,7 -193,60 +203,70 @@@: 'resource.move': 'resource.rename'- // Authorization with audited denials (spec: every authz denial is audited).+ let ifMatch: number | undefined+ if (patch.ifMatch !== undefined) {+ ifMatch = Number(patch.ifMatch)+ if (!Number.isInteger(ifMatch)) throw new ResourcePatchError(412, 'precondition_failed')+ }++ const requestedName = wantsRename ? validateName(patch.newName) : observedResource.name+ const requestedDestination = wantsMove ? String(patch.newParentId) : null+ 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)++ : null+ if (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')+ throw new ResourcePatchError(400, 'not_a_directory')+ const initialChains = await Promise.all([+ observedResource.parent_resource_id+ ? loadAncestorChain(db, observedResource.parent_resource_id)+ : Promise.resolve([]),+ requestedDestination ? loadAncestorChain(db, requestedDestination) : Promise.resolve([]),+ ])+ if (initialChains.flat().some(row => row.drive !== drive))+ throw new ResourcePatchError(412, 'precondition_failed')+ await lockRows(db, [+ resourceId,+ ...(observedResource.parent_resource_id ? [observedResource.parent_resource_id] : []),+ ...(requestedDestination ? [requestedDestination] : []),+ ...initialChains.flat().map(row => row.resource_id),+ ])++ const resource = await loadResource(db, resourceId)+ if (!resource || resource.deleted_at !== null || resource.drive !== drive)+ throw new ResourcePatchError(412, 'precondition_failed')+ if (+ resource.parent_resource_id !== observedResource.parent_resource_id ||+ resource.version !== observedResource.version+ )+ throw new ResourcePatchError(412, 'precondition_failed')+ if (resource.parent_resource_id === null) throw new ResourcePatchError(400, 'path_invalid')+ if (ifMatch !== undefined && ifMatch !== resource.version)+ throw new ResourcePatchError(412, 'precondition_failed')++ 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.name+ let newParentId: string | null = resource.parent_resource_id+ let parentChain = sourceChain+const requireAccess = async (bit: 'read' | 'write' | 'delete' | 'manage_acl' | 'share',rid: string@@@ -145,20 -262,23 +289,25 @@@}if (wantsMove) {- const dest = String(patch.newParentId)- if (!UUID_RE.test(dest)) throw new ResourcePatchError(400, 'path_invalid')- if (resource.parent_resource_id === null) throw new ResourcePatchError(400, 'path_invalid')+ const dest = requestedDestination!const destRow = await loadResource(db, dest)- if (!destRow) throw new ResourcePatchError(404, 'not_found')- if (destRow.drive !== resource.drive) throw new ResourcePatchError(403, 'cross_boundary')- if (destRow.kind !== 'directory') throw new ResourcePatchError(400, 'not_a_directory')- // Cycle guard: never move a resource into itself or one of its descendants- // (would orphan the subtree and loop ancestor traversal).- const destAncestors = await ancestorsOf(db, drive, dest)- if (dest === resourceId || destAncestors.includes(resourceId)) {+ const observedDest = observedDestination!+ if (+ !destRow ||+ destRow.deleted_at !== null ||+ destRow.drive !== observedDest.drive ||+ 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')}- // move authority: write+delete on source parent, write on destination parent.await requireAccess('write', resource.parent_resource_id)await requireAccess('delete', resource.parent_resource_id)await requireAccess('write', dest)@@@ -182,19 -300,13 +329,20 @@@}throw err}- if (updated.rows.length === 0) {- throw new ResourcePatchError(412, 'precondition_failed')- }+ if (updated.rows.length === 0) throw new ResourcePatchError(412, 'precondition_failed')const version = Number((updated.rows[0] as { version: number }).version)+ 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 }}diff --cc control-api/src/routes/gfs/seed.tsindex 7041cf500,9479a1ed3..8ee6d00c2--- a/control-api/src/routes/gfs/seed.ts+++ b/control-api/src/routes/gfs/seed.ts@@@ -30,17 -31,28 +31,24 @@@ export async function seedRootDirectoriif (!Array.isArray(b.rootDirectories) || b.rootDirectories.some(d => typeof d !== 'string')) {return { status: 400, body: { error: 'invalid_rootDirectories' } }}- const result = await seedRootDirectories(store, b.drive, b.rootDirectories as string[])- return { status: 200, body: result }+ try {+ const result = await seedRootDirectories(store, b.drive, b.rootDirectories as string[])+ return { status: 200, body: result }+ } catch (error) {+ if (error instanceof InvalidRootDirectoriesError) {+ return { status: 400, body: { error: 'invalid_rootDirectories' } }+ }+ throw error+ }}- export function registerGfsSeedRoute(router: Router): void {- router.post(- '/gfs/seed',- requireInternalControlJwt,- asyncHandler(async (req, res) => {- const result = await seedRootDirectoriesToHttp(new DbSeedResourceStore(pool), req.body)- res.status(result.status).json(result.body)- })+ export async function handleSeed(req: Request, res: Response): Promise<void> {+ const result = await withTransaction(db =>+ seedRootDirectoriesToHttp(new DbSeedResourceStore(db), req.body))+ res.status(result.status).json(result.body)+ }++ export function registerGfsSeedRoute(router: Router): void {- router.post(- '/gfs/seed',- requireInternalControlJwt,- asyncHandler(handleSeed)- )++ router.post('/gfs/seed', requireInternalControlJwt, asyncHandler(handleSeed))}diff --cc control-api/src/services/access/mcpInvocable.tsindex 59b40f90a,b8dc38219..53e36db5b--- a/control-api/src/services/access/mcpInvocable.ts+++ b/control-api/src/services/access/mcpInvocable.ts@@@ -13,10 -13,15 +13,15 @@@* - `spec.enabled !== false`* - `spec.auth.type` is absent or equals `"none"`* - `spec.transport.url` is a non-empty string- * - Session catalog returns **names only**; RPC catalog additionally returns- * the transport URL.+ * - Session catalog preserves names-only compatibility while enriching each+ * authorized agent with its canonical directory identity; RPC catalog+ * additionally returns the transport URL.*/import type { K8sGateway } from '../../k8s.js'+ import {- buildAgentDirectoryEntry,+ type AgentDirectoryEntry,++ buildAgentDirectoryEntry,+ } from '../directory/accessReconciliation.js'export interface InvocableMcpServer {name: string@@@ -185,22 -222,54 +222,48 @@@ export async function resolveMcpServersconst { mcpServersNamespace, hostsNamespace, agentNames } = optsif (agentNames.length === 0) return []- const [hosts, mcpServers] = await Promise.all([- gateway.listResource('hosts', hostsNamespace),- gateway.listResource('mcpservers', mcpServersNamespace),- ])- const hostList = asArray<HostCR>(hosts)- const serverList = asArray<McpServerCR>(mcpServers)+ 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 HostCR+ const directoryEntry = buildAgentDirectoryEntry(host, hostsNamespace)+ if (!directoryEntry || directoryEntry.name !== requestedName) return null+ return { host, directoryEntry }+ } catch (error) {+ if (isK8sResourceNotFound(error)) return null+ // A non-404 failure says nothing about whether this already-authorized+ // Host still exists. Propagate it so callers can preserve their+ // names-only compatibility field instead of silently revoking access.+ throw error+ }+ })+ )- const hostByName = new Map<string, HostCR>()- for (const h of hostList) {- const n = h.metadata?.name- if (n) hostByName.set(n, h)+ 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, or+ // a broken mcpservers list path reads as "this agent has no tools".+ console.error(+ '[mcpInvocable] mcpservers list failed; directory served without MCP catalog:',+ err instanceof Error ? err.message : String(err)+ )}+ const visibleHosts = resolvedHosts.filter(+ (+ item+ ): item is {+ host: HostCR+ directoryEntry: AgentDirectoryEntry+ } => item !== null+ )+const scopedContextIds = new Set<string>()- for (const agentName of agentNames) {- const contextRef = hostByName.get(agentName)?.spec?.contextRef+ for (const { host } of visibleHosts) {+ const contextRef = host.spec?.contextRefif (contextRef) scopedContextIds.add(contextRef)}diff --cc control-api/src/services/directory/accessReconciliation.tsindex 077fc75fc,60b77d793..e019fbeb1--- a/control-api/src/services/directory/accessReconciliation.ts+++ b/control-api/src/services/directory/accessReconciliation.ts@@@ -16,8 -21,62 +21,59 @@@ export type AccessPartition =deleted: string[]}+ export type AgentDirectoryEntry = {+ name: string+ namespace: string+ displayName: string+ active: true+ gfsSubject: {+ type: 'host'+ id: string+ }+ }++ // The legacy shared credential was never an individual Host identity. Keeping+ // it out of the directory prevents callers from turning fleet-wide history into+ // a selectable per-agent grant target.+ const LEGACY_FLEET_WIDE_HOST_SENTINEL = 'standalone'++ export function buildAgentDirectoryEntry(+ value: unknown,+ trustedNamespace: string+ ): AgentDirectoryEntry | null {+ if (!value || typeof value !== 'object') return null+ const host = value as HostResource+ 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 null+ if (reportedNamespace !== trustedNamespace) return null+ if (host.metadata?.deletionTimestamp) return null+ if (host.spec?.enabled === false) return null++ 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,+ displayName: configuredDisplayName || name,+ active: true,+ gfsSubject: { type: 'host', id: subjectId },+ }+ }+export const MAX_DELETED_ACCESS_HISTORY = 200+ export class DeletedAgentHistoryLimitError extends Error {+ constructor(public readonly limit: number) {+ super(`deleted agent history exceeds the ${limit}-entry limit`)+ this.name = 'DeletedAgentHistoryLimitError'+ }+ }+export function normalizeUnique(values: unknown[]): string[] {const seen = new Set<string>()const normalized: string[] = []diff --cc control-api/test/db.gfsAuditDecisionEvidenceMigration.test.tsindex 000000000,eeae409c4..edf8e6da5mode 000000,100644..100644--- a/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts+++ b/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts@@@ -1,0 -1,30 +1,30 @@@-import { readFileSync } from 'node:fs'+ import { describe, expect, it } from 'vitest'++import { readFileSync } from 'node:fs'++ describe('0073_gfs_audit_decision_evidence', () => {+ it('adds constrained decision evidence without rewriting existing audit rows', () => {+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')+ const previous = source.indexOf("version: '0072_gfs_reader_database_role'")+ const start = source.indexOf("version: '0073_gfs_audit_decision_evidence'")+ const sql = source.slice(start, source.indexOf('\n },\n]', start))++ expect(previous).toBeGreaterThan(-1)+ expect(start).toBeGreaterThan(previous)+ expect(sql).toContain("ADD COLUMN IF NOT EXISTS record_type TEXT NOT NULL DEFAULT 'legacy'")+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS matched_subject TEXT NULL')+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS authorization_source TEXT NULL')+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS cached_authorization_source TEXT NULL')+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS mutation_outcome TEXT NULL')+ expect(sql).toContain("'direct_grant', 'inherited_grant', 'direct_share'")+ expect(sql).toContain("'inherited_share', 'operator', 'cache'")+ expect(sql).toContain("mutation_outcome IN ('succeeded', 'failed')")+ expect(sql).toContain("record_type = 'authorization_decision' AND mutation_outcome IS NULL")+ expect(sql).toContain("record_type = 'mutation_outcome' AND mutation_outcome IS NOT NULL")+ expect(sql).toContain('GRANT INSERT ON gfs_audit TO gfs_controller, gfs_controller_reader')+ expect(sql).toContain(+ 'REVOKE UPDATE, DELETE, TRUNCATE ON gfs_audit\n FROM gfs_controller, gfs_controller_reader'+ )+ expect(sql).not.toMatch(/UPDATE\s+gfs_audit|DELETE\s+FROM\s+gfs_audit/i)+ expect(sql).not.toMatch(/DROP\s+(TABLE|COLUMN|CONSTRAINT)/i)+ })+ })diff --cc control-api/test/db.gfsBlobGenerationMigration.test.tsindex 000000000,1c6619078..03aac15e3mode 000000,100644..100644--- a/control-api/test/db.gfsBlobGenerationMigration.test.ts+++ b/control-api/test/db.gfsBlobGenerationMigration.test.ts@@@ -1,0 -1,21 +1,21 @@@-import { readFileSync } from 'node:fs'+ import { describe, expect, it } from 'vitest'++import { readFileSync } from 'node:fs'++ 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')+ expect(sql).toContain("split_part(blob_key, '/', 1) = replace(resource_id::text, '-', '')")+ expect(sql).toContain('CREATE TABLE IF NOT EXISTS gfs_blob_manifests')+ expect(sql).toContain('request_id UUID NOT NULL')+ expect(sql).toContain("state IN ('staged', 'committed', 'deleting')")+ expect(sql).toContain('UPDATE OF parent_resource_id, name, path_cache, deleted_at')+ expect(sql).toContain('GRANT SELECT, INSERT, UPDATE, DELETE ON gfs_blob_manifests')+ expect(sql).not.toMatch(/DROP\s+(TABLE|COLUMN)/i)+ })+ })diff --cc control-api/test/db.gfsReaderRoleMigration.test.tsindex 000000000,ba420391b..1ec5c2b7amode 000000,100644..100644--- a/control-api/test/db.gfsReaderRoleMigration.test.ts+++ b/control-api/test/db.gfsReaderRoleMigration.test.ts@@@ -1,0 -1,34 +1,34 @@@-import { readFileSync } from 'node:fs'+ import { describe, expect, it } from 'vitest'++import { readFileSync } from 'node:fs'++ describe('0072_gfs_reader_database_role', () => {+ it('adds a NOLOGIN least-privilege reader after immutable blob generations', () => {+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')+ const previous = source.indexOf("version: '0071_gfs_immutable_blob_generations'")+ const start = source.indexOf("version: '0072_gfs_reader_database_role'")+ const sql = source.slice(+ start,+ source.indexOf("version: '0073_gfs_audit_decision_evidence'", start)+ )++ expect(previous).toBeGreaterThan(-1)+ expect(start).toBeGreaterThan(previous)+ expect(sql).toContain('CREATE ROLE gfs_controller_reader NOLOGIN')+ expect(sql).toContain(+ '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'+ )+ expect(sql).toContain('GRANT SELECT (id, status) ON control_admin_users')+ expect(sql).toContain('GRANT SELECT (team_id, user_id, status) ON team_members')+ expect(sql).toContain('GRANT INSERT ON gfs_audit TO gfs_controller_reader')+ expect(sql).toContain('REVOKE ALL PRIVILEGES ON gfs_blob_manifests FROM gfs_controller_reader')+ expect(sql).toContain('REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON gfs_resources')+ expect(sql).toContain('REVOKE UPDATE, DELETE, TRUNCATE ON gfs_audit')+ expect(sql).not.toMatch(/ALTER ROLE gfs_controller\s/)+ expect(sql).not.toMatch(/DROP\s+(ROLE|TABLE|COLUMN)/i)+ })+ })diff --cc control-api/test/db.gfsRuntimeRoleContractMigration.test.tsindex 000000000,6d114ca47..ca8590d44mode 000000,100644..100644--- a/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts+++ b/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts@@@ -1,0 -1,47 +1,47 @@@-import { readFileSync } from 'node:fs'+ import { describe, expect, it } from 'vitest'++import { readFileSync } from 'node:fs'++ describe('0074_gfs_runtime_role_exact_contract', () => {+ it('normalizes both roles without changing credential state', () => {+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')+ const previous = source.indexOf("version: '0073_gfs_audit_decision_evidence'")+ const start = source.indexOf("version: '0074_gfs_runtime_role_exact_contract'")+ const sql = source.slice(start, source.indexOf('\n },\n]', start))++ expect(start).toBeGreaterThan(previous)+ expect(sql).toContain(+ 'ALTER ROLE gfs_controller\n NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'+ )+ expect(sql).toContain(+ 'ALTER ROLE gfs_controller_reader\n NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'+ )+ expect(sql).not.toMatch(/ALTER ROLE gfs_controller(?:_reader)?\s+(?:NO)?LOGIN/)+ expect(sql).not.toMatch(/ALTER\s+ROLE[^;]*PASSWORD|DROP\s+ROLE/i)+ expect(sql).toContain("ARRAY['gfs_controller', 'gfs_controller_reader']")+ expect(sql).toContain("EXECUTE format('REVOKE %I FROM %I'")+ })++ it('rebuilds exact table, sequence, audit, and subject-column grants', () => {+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')+ const start = source.indexOf("version: '0074_gfs_runtime_role_exact_contract'")+ const sql = source.slice(start, source.indexOf('\n },\n]', start))++ expect(sql).toContain(+ 'gfs_blob_manifests, gfs_audit FROM gfs_controller, gfs_controller_reader, PUBLIC'+ )+ expect(sql).toContain('GRANT SELECT, INSERT, UPDATE ON gfs_resources TO gfs_controller')+ expect(sql).toContain(+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON gfs_blob_manifests TO gfs_controller'+ )+ expect(sql).toContain(+ 'GRANT SELECT ON gfs_resources, gfs_grants, gfs_shares TO gfs_controller_reader'+ )+ expect(sql).toContain('GRANT INSERT ON gfs_audit TO gfs_controller_reader')+ expect(sql).toContain(+ 'GRANT SELECT (id, status) ON control_admin_users\n TO gfs_controller, gfs_controller_reader'+ )+ expect(sql).toContain(+ 'GRANT SELECT (team_id, user_id, status) ON team_members\n TO gfs_controller, gfs_controller_reader'+ )+ })+ })diff --cc control-api/test/deploy.gfsProvisioning.test.tsindex 748844875,ad629cbd9..587291b33--- a/control-api/test/deploy.gfsProvisioning.test.ts+++ b/control-api/test/deploy.gfsProvisioning.test.ts@@@ -1,5 -1,7 +1,7 @@@import { describe, expect, it } from 'vitest'-import { readFileSync } from 'node:fs'+ import { spawnSync } from 'node:child_process'+import { readFileSync } from 'node:fs'+ import { fileURLToPath } from 'node:url'function read(relativeFromRepoRoot: string): string {return readFileSync(new URL(relativeFromRepoRoot, import.meta.url), 'utf-8')@@@ -7,22 -9,162 +9,219 @@@describe('deploy/scripts/provision-gfs-db.sh', () => {const script = read('../../deploy/scripts/provision-gfs-db.sh')+ const verifier = read('../../scripts/minikube/verify-gfs.sh')+ const probe = read('../../deploy/scripts/lib/gfs-dsn-probe.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)+ const uri = (endpoint: string) => ['postgresql', '://', role, ':', password, endpoint].join('')- it('keeps process argv free of generated connection material', () => {- expect(script).toContain('exec -i "$PG_DEPLOY" -- psql')- expect(script).toContain('-f - <<SQL')- expect(script).toContain('--patch-file=/dev/stdin')- expect(script).not.toContain(' -c \\')- expect(script).not.toContain('-p "$patch"')- expect(script).not.toContain(`CONN="$${'D'}${'SN'}"`)+ it('requires an explicit mode and contains no broad rollout', () => {+ expect(script).toContain('stage-writer|stage-reader|rotate-reader|rotate-writer')+ expect(script).not.toContain('rollout restart deployment -l')+ expect(script).not.toContain('rollout status deployment -l')+ expect(script).not.toContain('base64 -d 2>/dev/null || true')})- it('fails loud when gfsc rollout status fails', () => {- const rolloutLine = script- .split('\n')- .find(line => line.includes('rollout status deployment -l "$GFS_DEPLOY_SELECTOR"'))+ 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')")+ expect(script).toContain("has_table_privilege(:'role_name', 'gfs_blob_manifests', 'DELETE')")+ expect(script).toContain(+ "has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"+ )+ expect(script).toContain(+ "has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"+ )+ expect(script).toContain("column_name NOT IN ('id', 'status')")+ expect(script).toContain("column_name NOT IN ('team_id', 'user_id', 'status')")+ expect(script).toContain("'INSERT,UPDATE,REFERENCES'")+ expect(script).toContain("'DELETE,TRUNCATE,TRIGGER'")+ })++ it('fails API and decoding errors instead of treating them as absence', () => {+ expect(script).toContain('cannot read ${GFS_NS}/$secret')+ expect(script).toContain('contains an invalid $key encoding')+ expect(script).toContain('[ -n "$encoded" ] || return 0')+ })++ 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"')+ expect(script).not.toContain('DSN_TO_CHECK=')+ expect(script).not.toContain('-v role_secret="$password"')+ expect(script).not.toContain('PGPASSWORD=')+ expect(script).not.toContain('psql "$dsn"')+ expect(script).not.toContain('psql "$probe_dsn"')+ expect(script).not.toContain('-c "SELECT rolcanlogin')+ expect(script).toContain('-v role_name="$1" -f -')+ expect(probe).toContain('if not raw or "\\\\" in raw')+ expect(probe).toContain('ch.isspace() or unicodedata.category(ch).startswith("C")')+ expect(probe).toContain('parsed.hostname == expected_host')+ expect(probe).toContain('and not parsed.query')+ expect(probe).toContain('and not parsed.fragment')+ expect(probe).toContain('re.fullmatch(r"[0-9a-f]{48}", password)')+ expect(verifier).toContain('gfs_dsn_authenticates_as "$dsn" "$role"')+ expect(verifier).not.toContain('psql "$connection"')+ expect(verifier).toContain('clerum\\.io/gfs-dsn-rotated-at')+ expect(verifier).toContain('GlobalFileSystem/gfs is not adopted; no GFS instance to verify')+ expect(verifier).toContain('cannot determine whether GlobalFileSystem/gfs is adopted')+ expect(verifier).toContain('credential lifecycle is ${lifecycle:-unset}, not ready')+ expect(verifier).toContain('retains an unfinished credential candidate')+ expect(script).toContain('pending-connection-string')+ expect(script).toContain('Resuming persisted pending candidate')+ expect(script).toContain('Resuming incomplete ${deployment} rollout without rotating again')+ expect(script).toContain('rollback_uncommitted_candidate')+ expect(script).toContain('staged credential state was superseded; refusing a stale completion')+ expect(script).not.toContain('Adopting concurrently staged candidate')+ expect(script).toContain('GFS_RECOVER_ABANDONED_STATE')+ expect(recovery).toContain('role_can_login "$role"')+ expect(recovery).toContain('release_abandoned_candidate "$secret"')+ 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')+ expect(script.match(/SELECT 1\/0;/g)).toHaveLength(4)+ })- expect(rolloutLine).toBeDefined()- expect(rolloutLine).not.toContain('|| true')+ 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('')+ for (const endpoint of [+ '@wrong.example:5432/profiles',+ '@[::1]:5432/profiles',+ `@${host}:5433/profiles`,+ `@${host}/profiles`,+ `@${host}:5432/wrong`,+ `@${host}:5432/profiles?host=example.invalid`,+ `@${host}:5432/profiles#override`,+ `@${host}:not-a-port/profiles`,+ ]) {+ expect(run(uri(endpoint)).status).not.toBe(0)+ }+ expect(run(`postgresql://other:${password}@${host}:5432/profiles`).status).not.toBe(0)+ expect(run(`postgresql://${role}:@${host}:5432/profiles`).status).not.toBe(0)+ expect(run(`postgresql://${role}:short@${host}:5432/profiles`).status).not.toBe(0)+ expect(run(`postgresql://${role}:${'A'.repeat(48)}@${host}:5432/profiles`).status).not.toBe(0)+ expect(run(`postgresql://${role}:${'%3B'.repeat(48)}@${host}:5432/profiles`).status).not.toBe(0)+ expect(run(`${uri(`@${host}:5432/profiles`)}\n`).status).not.toBe(0)})})diff --cc control-api/test/gfs.seedResources.test.tsindex bdfddd3bc,45bf57b17..6f31d07d5--- a/control-api/test/gfs.seedResources.test.ts+++ b/control-api/test/gfs.seedResources.test.ts@@@ -139,7 -189,7 +189,13 @@@ describe('DbSeedResourceStore.ensureDirit('fails loud if neither insert nor select yields a row (no silent empty id)', async () => {const db = new FakeDb()- db.responses = [{ rows: [] }, { rows: [] }]- 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 --cc control-api/test/gfs.seedRouteTransaction.test.tsindex 000000000,759f03668..7fa87145emode 000000,100644..100644--- a/control-api/test/gfs.seedRouteTransaction.test.ts+++ b/control-api/test/gfs.seedRouteTransaction.test.ts@@@ -1,0 -1,85 +1,84 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest'++import { handleSeed } from '../src/routes/gfs/seed.js'++ const state = vi.hoisted(() => {+ const events: string[] = []+ const db = {+ query: vi.fn(async (text: string) => {+ if (text.includes('pg_advisory_xact_lock')) {+ events.push('advisory')+ return { rows: [] }+ }+ if (text.includes('ORDER BY resource_id FOR UPDATE')) {+ events.push('root-lock')+ return { rows: [] }+ }+ if (text.includes('INSERT INTO gfs_resources')) {+ events.push('insert')+ if (state.failInsert) throw new Error('insert_failed')+ return { rows: [{ resource_id: 'root-1' }] }+ }+ return { rows: [] }+ }),+ }+ return { db, events, failInsert: false }+ })++ vi.mock('../src/db.js', () => ({+ withTransaction: vi.fn(async (work: (db: typeof state.db) => Promise<unknown>) => {+ state.events.push('begin')+ try {+ const result = await work(state.db)+ state.events.push('commit')+ return result+ } catch (error) {+ state.events.push('rollback')+ throw error+ }+ }),+ }))++ 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,+ body: undefined as unknown,+ status(code: number) {+ this.code = code+ return this+ },+ json(body: unknown) {+ this.body = body+ return this+ },+ }+ }++ describe('gfs seed route transaction boundary', () => {+ beforeEach(() => {+ state.events.length = 0+ state.failInsert = false+ state.db.query.mockClear()+ })++ it('uses one transaction client for lock and seed publication', async () => {+ const res = response()+ await handleSeed({ body: { drive: 'main', rootDirectories: [] } } as never, res as never)+ expect(res.code).toBe(200)+ expect(state.events).toEqual(['begin', 'advisory', 'root-lock', 'insert', 'commit'])+ expect(state.db.query).toHaveBeenCalledTimes(3)+ })++ it('rolls back when seed publication fails', async () => {+ state.failInsert = true+ const res = response()+ await expect(+ handleSeed({ body: { drive: 'main', rootDirectories: [] } } as never, res as never)+ ).rejects.toThrow('insert_failed')+ expect(state.events).toEqual(['begin', 'advisory', 'root-lock', 'insert', 'rollback'])+ expect(res.code).toBe(0)+ })+ })diff --cc control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.tsindex 000000000,0e5168b45..8ed4db116mode 000000,100644..100644--- a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts+++ b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts@@@ -1,0 -1,187 +1,189 @@@-import { randomBytes } from 'node:crypto'+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { randomBytes } from 'node:crypto'+ import { Pool, type PoolClient } from 'pg'+ import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'++ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip++ function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ async function asRole<T>(pool: Pool, role: string, run: (client: PoolClient) => Promise<T>) {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query(`SET LOCAL ROLE ${quoteIdent(role)}`)+ const result = await run(client)+ await client.query('COMMIT')+ return result+ } catch (error) {+ await client.query('ROLLBACK').catch(() => undefined)+ throw error+ } finally {+ client.release()+ }+ }++ describeRealPostgres('GFS typed audit decision evidence', () => {+ const database = `gfs_audit_evidence_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let pool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ }, 60_000)++ afterAll(async () => {+ await pool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('is additive, idempotent, and constrains the evidence vocabulary', async () => {+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0073_gfs_audit_decision_evidence'+ )+ expect(migration).toBeDefined()+ await migration!.apply(pool)++ const columns = await pool.query(+ `SELECT column_name, is_nullable, column_default+ FROM information_schema.columns+ WHERE table_schema = 'public'+ 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({+ is_nullable: 'NO',+ column_default: "'legacy'::text",+ })++ const constraints = await pool.query(+ `SELECT conname+ FROM pg_constraint+ WHERE conrelid = 'gfs_audit'::regclass+ AND conname LIKE 'gfs_audit_%_valid'`+ )+ expect(new Set(constraints.rows.map(row => row.conname))).toEqual(+ new Set([+ 'gfs_audit_record_type_valid',+ 'gfs_audit_authorization_source_valid',+ 'gfs_audit_cached_authorization_source_valid',+ 'gfs_audit_mutation_outcome_valid',+ 'gfs_audit_record_type_fields_valid',+ ])+ )++ await pool.query(+ `INSERT INTO gfs_audit (subject, op, outcome, row_hash)+ VALUES ('host:legacy', 'read', 'allow', 'legacy-hash')`+ )+ const legacy = await pool.query(+ `SELECT record_type, matched_subject, authorization_source,+ cached_authorization_source, mutation_outcome+ FROM gfs_audit WHERE row_hash = 'legacy-hash'`+ )+ expect(legacy.rows[0]).toEqual({+ record_type: 'legacy',+ matched_subject: null,+ authorization_source: null,+ cached_authorization_source: null,+ mutation_outcome: null,+ })++ await expect(+ pool.query(+ `INSERT INTO gfs_audit+ (subject, op, outcome, row_hash, record_type, authorization_source)+ VALUES ('host:bad', 'read', 'allow', 'bad-source',+ 'authorization_decision', 'standalone')`+ )+ ).rejects.toMatchObject({ code: '23514' })+ await expect(+ pool.query(+ `INSERT INTO gfs_audit+ (subject, op, outcome, row_hash, record_type, authorization_source)+ VALUES ('host:bad', 'read', 'allow', 'cache-without-source',+ 'authorization_decision', 'cache')`+ )+ ).rejects.toMatchObject({ code: '23514' })+ })++ it.each(['gfs_controller', 'gfs_controller_reader'])(+ '%s can append typed evidence but cannot update or delete it',+ async role => {+ const rowHash = `${role}-decision-${randomBytes(4).toString('hex')}`+ await asRole(pool, role, client =>+ client.query(+ `INSERT INTO gfs_audit+ (subject, op, outcome, row_hash, record_type, matched_subject,+ authorization_source, cached_authorization_source)+ VALUES ('host:actor', 'read', 'allow', $1, 'authorization_decision',+ 'host:actor', 'cache', 'direct_grant')`,+ [rowHash]+ )+ )++ await expect(+ asRole(pool, role, client =>+ client.query(`UPDATE gfs_audit SET outcome = 'deny' WHERE false`)+ )+ ).rejects.toMatchObject({ code: '42501' })+ await expect(+ asRole(pool, role, client => client.query(`DELETE FROM gfs_audit WHERE false`))+ ).rejects.toMatchObject({ code: '42501' })+ }+ )++ it('records actual mutation outcome separately from the authorization decision', async () => {+ await asRole(pool, 'gfs_controller', client =>+ client.query(+ `INSERT INTO gfs_audit+ (subject, op, outcome, row_hash, record_type, matched_subject,+ authorization_source, mutation_outcome)+ VALUES ('host:actor', 'copy', 'error', 'mutation-failed', 'mutation_outcome',+ 'host:actor', 'direct_grant', 'failed')`+ )+ )+ await expect(+ pool.query(+ `INSERT INTO gfs_audit+ (subject, op, outcome, row_hash, record_type, mutation_outcome)+ VALUES ('host:bad', 'copy', 'allow', 'decision-with-mutation',+ 'authorization_decision', 'succeeded')`+ )+ ).rejects.toMatchObject({ code: '23514' })+ })+ })diff --cc control-api/test/gfsBlobMigration.realPostgres.integration.test.tsindex 000000000,1d9bea0e4..20eea0d10mode 000000,100644..100644--- a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts+++ b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts@@@ -1,0 -1,139 +1,159 @@@-import { randomBytes, randomUUID } from 'node:crypto'+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { randomBytes, randomUUID } from 'node:crypto'+ import { Pool } from 'pg'+ import { initDb } from '../src/db.js'++ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip++ function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {+ const database = `gfs_blob_migration_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let pool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ const connector = { connect: () => pool.connect() }+ await initDb(connector)+ await initDb(connector)+ }, 60_000)++ afterAll(async () => {+ await pool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('applies 0068 exactly once with named constraints, indexes, and writer ACL', async () => {+ const versions = await pool.query<{ count: string }>(+ `SELECT count(*)::text AS count FROM schema_migrations+ WHERE version = '0071_gfs_immutable_blob_generations'`+ )+ expect(versions.rows).toEqual([{ count: '1' }])++ const columns = await pool.query<{ column_name: string; is_nullable: string }>(+ `SELECT column_name,is_nullable FROM information_schema.columns+ WHERE table_schema='public' AND table_name='gfs_blob_manifests'+ 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')++ const constraints = await pool.query<{ conname: string; definition: string }>(+ `SELECT conname,pg_get_constraintdef(oid) AS definition FROM pg_constraint+ WHERE conrelid IN ('gfs_resources'::regclass,'gfs_blob_manifests'::regclass)+ AND conname IN ('gfs_resources_blob_metadata_pair','gfs_blob_manifests_blob_key_valid')+ 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+ )++ const indexes = await pool.query<{ indexname: string; indexdef: string }>(+ `SELECT indexname,indexdef FROM pg_indexes WHERE schemaname='public'+ AND indexname IN ('gfs_resources_blob_key_uniq','gfs_blob_manifests_cleanup_idx')+ 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)')++ const acl = await pool.query<Record<string, boolean>>(`+ SELECT has_table_privilege('gfs_controller','gfs_resources','SELECT') AS resource_read,+ has_table_privilege('gfs_controller','gfs_resources','INSERT') AS resource_insert,+ has_table_privilege('gfs_controller','gfs_resources','UPDATE') AS resource_update,+ has_table_privilege('gfs_controller','gfs_resources','DELETE') AS resource_delete,+ has_table_privilege('gfs_controller','gfs_blob_manifests','SELECT') AS manifest_read,+ has_table_privilege('gfs_controller','gfs_blob_manifests','INSERT') AS manifest_insert,+ 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,+ })+ })++ it('enforces generation ownership and permits only typed legacy cleanup candidates', async () => {+ const rootId = randomUUID()+ const resourceId = randomUUID()+ const drive = `blob-shape-${randomBytes(4).toString('hex')}`+ await pool.query(+ `INSERT INTO gfs_resources(resource_id,drive,parent_resource_id,name,kind,path_cache)+ VALUES ($1,$3,NULL,'','directory','/'),($2,$3,$1,'file.txt','file','/file.txt')`,+ [rootId, resourceId, drive]+ )+ const compactId = resourceId.replaceAll('-', '')+ const generationKey = `${compactId}/${randomUUID()}`+ await pool.query(+ `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)+ VALUES ($1,$2,$3,'generation',$4,1,'staged'),+ ($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 --cc control-api/test/gfsBlobReconciliation.realPostgres.integration.test.tsindex 000000000,5007419cf..9b66ae892mode 000000,100644..100644--- a/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts+++ b/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts@@@ -1,0 -1,229 +1,234 @@@++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 { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'-import { initDb } from '../src/db.js'-import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'+ import { reconcileExpiredBlobs } from '../../gfs-controller/src/db/blobReconciliation.js'++import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'++import type { GfsMetrics } from '../../gfs-controller/src/metrics.js'+ import { BlobStore } from '../../gfs-controller/src/storage/blobStore.js'+ import { resolveBlobKeyPath, resolveBlobPath } from '../../gfs-controller/src/storage/paths.js'-import type { GfsMetrics } from '../../gfs-controller/src/metrics.js'++import { initDb } from '../src/db.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+ // orphan-vs-referenced predicate and its real byte deletion were only ever+ // exercised against a FakeDb with a stubbed deleteByKey. Here it runs against a+ // real Postgres schema + a real on-disk BlobStore, asserting business-truth:+ // actual bytes on the PVC and actual manifest rows.+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip++ function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ // reconcileExpiredBlobs only calls setOrphanCandidates + recordBlobCleanupFailure;+ // a minimal recording stub keeps the test off prom-client while still proving the+ // failure counter is never touched on the happy paths.+ function metricsStub(): { metrics: GfsMetrics; failures: number } {+ const state = { failures: 0 }+ const metrics = {+ setOrphanCandidates: () => undefined,+ recordBlobCleanupFailure: () => {+ state.failures += 1+ },+ } as unknown as GfsMetrics+ return {+ metrics,+ get failures() {+ return state.failures+ },+ }+ }++ 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: Pool+ let pool: Pool+ let blobRoot: string+ let blobs: BlobStore+ let manifests: PgBlobStagingStore++ // Age a just-staged manifest so it clears the reconciler's `updated_at <+ // now() - olderThanMs` gate deterministically (no sleep, no flake).+ async function ageCandidate(blobKey: string): Promise<void> {+ await pool.query(+ `UPDATE gfs_blob_manifests SET updated_at = now() - interval '1 hour' WHERE blob_key = $1`,+ [blobKey]+ )+ }++ async function manifestExists(blobKey: string): Promise<boolean> {+ const res = await pool.query('SELECT 1 FROM gfs_blob_manifests WHERE blob_key = $1', [blobKey])+ return (res.rowCount ?? 0) > 0+ }++ 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+ }++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ blobRoot = await mkdtemp(join(tmpdir(), 'gfs-recon-real-pg-'))+ blobs = new BlobStore(blobRoot, 'writer')+ manifests = new PgBlobStagingStore(pool)+ }, 60_000)++ afterEach(async () => {+ // Reconciliation scans the whole table; isolate each case's business-truth by+ // clearing manifests + resources between cases (orphaned bytes with unique+ // UUIDs left on disk cannot collide with the next case's assertions).+ await pool.query('TRUNCATE gfs_blob_manifests, gfs_resources CASCADE')+ })++ afterAll(async () => {+ await pool?.end()+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('reaps an orphaned generation blob: deletes the real bytes AND removes the manifest row', async () => {+ const resourceId = randomUUID()+ const payload = randomBytes(96)+ const written = await blobs.writeImmutable(resourceId, randomUUID(), payload)+ await manifests.recordStaged({+ blobKey: written.blobKey,+ requestId: randomUUID(),+ resourceId,+ candidateKind: 'generation',+ contentSha256: written.contentSha256,+ bytes: written.bytes,+ })+ await ageCandidate(written.blobKey)++ // Precondition: real bytes on disk, manifest row present, NO gfs_resources+ // row references this blob_key (it is a genuine orphan).+ const blobPath = resolveBlobKeyPath(blobRoot, written.blobKey)+ expect(existsSync(blobPath)).toBe(true)+ expect(await manifestExists(written.blobKey)).toBe(true)++ const recorder = metricsStub()+ const result = await reconcileExpiredBlobs(manifests, blobs, recorder.metrics, {+ olderThanMs: 1000,+ limit: 16,+ })++ expect(result.deleted).toBe(1)+ expect(result.failures).toBe(0)+ // Read the recording stub too: the reconciler's failure metric must stay+ // untouched, not just its returned tally.+ expect(recorder.failures).toBe(0)+ // Business-truth: the bytes are gone from the PVC and the manifest row is gone.+ expect(existsSync(blobPath)).toBe(false)+ expect(await manifestExists(written.blobKey)).toBe(false)+ })++ it('never deletes a generation blob still referenced by a live resource', async () => {+ const rootId = randomUUID()+ const fileId = randomUUID()+ const drive = `recon-ref-${randomBytes(4).toString('hex')}`+ const payload = randomBytes(96)+ const written = await blobs.writeImmutable(fileId, randomUUID(), payload)+ await manifests.recordStaged({+ blobKey: written.blobKey,+ requestId: randomUUID(),+ resourceId: fileId,+ candidateKind: 'generation',+ contentSha256: written.contentSha256,+ bytes: written.bytes,+ })+ // A live gfs_resources row references the blob_key — this must protect it.+ await pool.query(+ `INSERT INTO gfs_resources+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, blob_key, content_sha256)+ VALUES+ ($1,$3,NULL,'','directory','/',0,0,NULL,NULL),+ ($2,$3,$1,'ref.txt','file','/ref.txt',1,$4,$5,$6)`,+ [rootId, fileId, drive, written.bytes, written.blobKey, written.contentSha256]+ )+ await ageCandidate(written.blobKey)++ const blobPath = resolveBlobKeyPath(blobRoot, written.blobKey)+ const recorder = metricsStub()+ const result = await reconcileExpiredBlobs(manifests, blobs, recorder.metrics, {+ olderThanMs: 1000,+ limit: 16,+ })++ // The real NOT EXISTS predicate must exclude the referenced blob from the+ // delete claim, so no bytes are deleted and the bytes survive on the PVC.+ expect(result.deleted).toBe(0)+ expect(result.failures).toBe(0)+ // Read the recording stub too: the reconciler's failure metric must stay+ // untouched, not just its returned tally.+ expect(recorder.failures).toBe(0)+ // Business-truth that matters: the bytes are protected.+ expect(existsSync(blobPath)).toBe(true)+ // The now-redundant staged manifest IS metadata-GC'd by removeCommittedMetadata+ // (the gfs_resources.blob_key reference is the source of truth) — only the+ // bytes are protected, never re-deleted. This asserts the GC does NOT touch bytes.+ expect(await manifestExists(written.blobKey)).toBe(false)+ })++ it('reaps a legacy_flat orphan through the legacy predicate and deletes the flat bytes', async () => {+ const resourceId = randomUUID()+ const legacyPath = resolveBlobPath(blobRoot, resourceId)+ // A legacy_flat blob's manifest key IS the dash-stripped resource id (the+ // blob_key_valid CHECK: `blob_key = replace(resource_id,'-','')`); legacy+ // candidates carry no committed digest (content_sha256 IS NULL).+ const legacyBlobKey = resourceId.replace(/-/g, '')+ await writeFile(legacyPath, randomBytes(48), { mode: 0o600 })+ await manifests.recordStaged({+ blobKey: legacyBlobKey,+ requestId: randomUUID(),+ resourceId,+ candidateKind: 'legacy_flat',+ contentSha256: null,+ bytes: 48,+ })+ await ageCandidate(legacyBlobKey)++ expect(existsSync(legacyPath)).toBe(true)+ const recorder = metricsStub()+ const result = await reconcileExpiredBlobs(manifests, blobs, recorder.metrics, {+ olderThanMs: 1000,+ limit: 16,+ })++ expect(result.deleted).toBe(1)+ expect(result.failures).toBe(0)+ // Read the recording stub too: the reconciler's failure metric must stay+ // untouched, not just its returned tally.+ expect(recorder.failures).toBe(0)+ // Business-truth: the flat legacy bytes are gone and the manifest row is gone.+ expect(existsSync(legacyPath)).toBe(false)+ expect(await manifestExists(legacyBlobKey)).toBe(false)+ expect(await manifestState(legacyBlobKey)).toBeNull()+ })+ })diff --cc control-api/test/gfsCopy.realPostgres.integration.test.tsindex 000000000,710a2463a..50a7399a0mode 000000,100644..100644--- a/control-api/test/gfsCopy.realPostgres.integration.test.ts+++ b/control-api/test/gfsCopy.realPostgres.integration.test.ts@@@ -1,0 -1,374 +1,408 @@@++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_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip++ function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ function compact(id: string): string {+ return id.replaceAll('-', '').toLowerCase()+ }++ async function readAll(stream: NodeJS.ReadableStream): Promise<Buffer> {+ const chunks: Buffer[] = []+ for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))+ return Buffer.concat(chunks)+ }++ interface SeededTree {+ drive: string+ rootId: string+ sourceId: string+ nestedId: string+ firstFileId: string+ secondFileId: string+ destinationId: string+ files: Map<string, Buffer>+ }++ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem blobs', () => {+ const database = `gfs_copy_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let pool: Pool+ let blobRoot: string+ let blobs: BlobStore+ let resources: PgResourceStore+ let writes: GfsWriteService+ let audit: DbAuditSink++ async function seedTree(label: string): Promise<SeededTree> {+ const tree: SeededTree = {+ drive: `copy-${label}-${randomBytes(4).toString('hex')}`,+ rootId: randomUUID(),+ sourceId: randomUUID(),+ nestedId: randomUUID(),+ firstFileId: randomUUID(),+ secondFileId: randomUUID(),+ destinationId: randomUUID(),+ files: new Map([+ ['first', Buffer.from(`first-${label}`)],+ ['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,+ bytes, blob_key, content_sha256)+ VALUES+ ($1,$7,NULL,'','directory','/',0,0,NULL,NULL),+ ($2,$7,$1,'source','directory','/source',3,0,NULL,NULL),+ ($3,$7,$2,'nested','directory','/source/nested',0,0,NULL,NULL),+ ($4,$7,$2,'first.txt','file','/source/first.txt',1,$8,$9,$10),+ ($5,$7,$3,'second.txt','file','/source/nested/second.txt',2,$11,$12,$13),+ ($6,$7,$1,'archive','directory','/archive',0,0,NULL,NULL)`,+ [+ tree.rootId,+ tree.sourceId,+ tree.nestedId,+ tree.firstFileId,+ tree.secondFileId,+ tree.destinationId,+ tree.drive,+ firstBlob.bytes,+ firstBlob.blobKey,+ firstBlob.contentSha256,+ secondBlob.bytes,+ secondBlob.blobKey,+ secondBlob.contentSha256,+ ]+ )+ return tree+ }++ async 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,+ plan: preflightCopy({+ drive: tree.drive,+ sourceResourceId: tree.sourceId,+ destinationParentId: tree.destinationId,+ newName,+ ifMatch: 3,+ snapshot,+ destination,+ maxObjects: 1_000,+ maxBytes: 1_073_741_824,+ deadlineAtMs: Date.now() + 30_000,+ nowMs: Date.now(),+ }),+ }+ }++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ blobRoot = await mkdtemp(join(tmpdir(), 'gfs-copy-real-pg-'))+ blobs = new BlobStore(blobRoot, 'writer')+ resources = new PgResourceStore(pool)+ audit = new DbAuditSink(pool)+ writes = new GfsWriteService(new PgTransactor(pool), blobs, new PgBlobStagingStore(pool))+ }, 60_000)++ afterAll(async () => {+ await pool?.end()+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('publishes a recursive copy atomically, preserves the source, and records success in the publication transaction', async () => {+ const tree = await seedTree('success')+ const before = await pool.query(+ `SELECT resource_id, parent_resource_id, path_cache, version, bytes, blob_key, content_sha256+ FROM gfs_resources WHERE drive=$1 ORDER BY resource_id`,+ [tree.drive]+ )+ const frozen = await planFor(tree, 'source-copy')+ const requestId = randomUUID()+ const result = await 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,+ })++ expect(result).toMatchObject({ objectCount: 4, fileCount: 2, folderCount: 2 })+ expect(result.totalBytes).toBe(+ BigInt(tree.files.get('first')!.length + tree.files.get('second')!.length)+ )+ const sourceAfter = await pool.query(+ `SELECT resource_id, parent_resource_id, path_cache, version, bytes, blob_key, content_sha256+ FROM gfs_resources WHERE drive=$1 AND path_cache NOT LIKE '/archive/source-copy%' ORDER BY resource_id`,+ [tree.drive]+ )+ expect(sourceAfter.rows).toEqual(before.rows)++ const copied = await pool.query(+ `SELECT resource_id, parent_resource_id, path_cache, kind, bytes, blob_key, content_sha256, xmin::text AS txid+ FROM gfs_resources WHERE drive=$1 AND path_cache LIKE '/archive/source-copy%'+ ORDER BY path_cache`,+ [tree.drive]+ )+ expect(copied.rows.map(row => row.path_cache)).toEqual([+ '/archive/source-copy',+ '/archive/source-copy/first.txt',+ '/archive/source-copy/nested',+ '/archive/source-copy/nested/second.txt',+ ])- 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)++ 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))++ 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()+ )++ const outcome = await pool.query(+ `SELECT op, record_type, mutation_outcome, request_id, xmin::text AS txid+ FROM gfs_audit WHERE request_id=$1`,+ [requestId]+ )+ expect(outcome.rows).toHaveLength(1)+ expect(outcome.rows[0]).toMatchObject({+ op: 'copy',+ record_type: 'mutation_outcome',+ mutation_outcome: 'succeeded',+ request_id: requestId,+ })+ expect(new Set(copied.rows.map(row => row.txid))).toEqual(new Set([outcome.rows[0]?.txid]))+ })++ it('rejects a destination collision before staging or publishing any node', async () => {+ const tree = await seedTree('collision')+ await pool.query(+ `INSERT INTO gfs_resources(resource_id,drive,parent_resource_id,name,kind,path_cache,version,bytes)+ VALUES ($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)`,+ [tree.drive]+ )+ expect(after.rows).toEqual(before.rows)+ expect(manifests.rows[0]?.count).toBe(0)+ })++ it('fails on a changed source version and leaves no copied metadata or staged blobs', async () => {+ const 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+ WHERE drive=$1 AND path_cache LIKE '/archive/stale-copy%'`,+ [tree.drive]+ )+ const manifests = await pool.query(+ `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' }])+ })++ // Concurrency — the optimistic If-Match path. replace() locks the row and+ // re-checks the version inside the writer transaction; two replaces of the+ // same file racing with the SAME If-Match can only be adjudicated by real row+ // locks, so this belongs in the real-PG suite, not the scripted-client unit.+ it('serializes two concurrent replaces of the same file: one version bump, the loser is precondition_failed', async () => {+ const tree = await seedTree('race-replace')+ // first.txt was seeded at version 1. Each replace runs on its own pooled+ // connection: the writer that locks the row first bumps version 1->2 and+ // commits; the other then sees version 2 != If-Match 1 and must fail.+ const fileId = tree.firstFileId+ const contentA = Buffer.from('replacement-A-payload')+ const contentB = Buffer.from('replacement-B-different-length')+ const attempt = (content: Buffer) =>+ writes.replace({ drive: tree.drive, resourceId: fileId, ifMatch: 1, content })++ const results = await Promise.allSettled([attempt(contentA), attempt(contentB)])+ const fulfilled = results.filter(+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof writes.replace>>> =>+ r.status === 'fulfilled'+ )+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')+ expect(fulfilled).toHaveLength(1)+ expect(rejected).toHaveLength(1)+ expect(rejected[0]!.reason).toMatchObject({ code: 'precondition_failed' })++ // Business truth: version bumped exactly once (1->2), and the bytes served+ // from the real blob store are the winner's — never a torn blend.+ const row = await pool.query(+ `SELECT version, bytes, blob_key FROM gfs_resources WHERE drive=$1 AND resource_id=$2`,+ [tree.drive, fileId]+ )+ expect(Number(row.rows[0]?.version)).toBe(2)+ const served = await readAll(await blobs.read(fileId, String(row.rows[0]?.blob_key)))+ expect([contentA, contentB].some(candidate => candidate.equals(served))).toBe(true)+ expect(Number(row.rows[0]?.bytes)).toBe(served.length)+ })++ // Concurrency — the per-drive advisory lock + destination re-check. Two copies+ // into the SAME destination name, both passing preflight before either+ // publishes, must not both land.+ it('serializes two concurrent copies into the same destination name: one wins, the loser is already_exists', async () => {+ const tree = await seedTree('race-copy')+ // Independent frozen plans for the same '/archive/dup' name. Under the+ // per-drive advisory lock the first copy inserts the subtree; the second+ // re-checks the destination name inside the writer txn, finds it taken, and+ // fails already_exists — the loser inserts nothing.+ const planA = await planFor(tree, 'dup')+ const planB = await planFor(tree, 'dup')+ const attempt = (plan: Awaited<ReturnType<typeof planFor>>, tag: string) =>+ writes.copy({+ requestId: randomUUID(),+ subject: `host:sandbox-recipes/copy-race-${tag}`,+ audit,+ drive: tree.drive,+ destinationParentId: tree.destinationId,+ plan: plan.plan,+ destination: plan.destination,+ deadlineAtMs: Date.now() + 30_000,+ })++ const results = await Promise.allSettled([attempt(planA, 'a'), attempt(planB, 'b')])+ const fulfilled = results.filter(+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof writes.copy>>> =>+ r.status === 'fulfilled'+ )+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')+ expect(fulfilled).toHaveLength(1)+ expect(rejected).toHaveLength(1)+ expect(rejected[0]!.reason).toMatchObject({ code: 'already_exists' })++ // Business truth: exactly ONE copied subtree root exists at the contended+ // destination name.+ const roots = await pool.query(+ `SELECT count(*)::integer AS n FROM gfs_resources WHERE drive=$1 AND path_cache='/archive/dup'`,+ [tree.drive]+ )+ expect(roots.rows[0]?.n).toBe(1)+ })+ })diff --cc control-api/test/gfsGrants.test.tsindex 728e658ad,93781d5fc..4a8f0bdc1--- a/control-api/test/gfsGrants.test.ts+++ b/control-api/test/gfsGrants.test.ts@@@ -642,6 -770,31 +770,33 @@@ describe('assertMayGrant — agent (hos).resolves.toBeUndefined()})+ 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(+ assertMayGrant(+ db,+ user('owner'),+ 'main',+ R,+ perms('manage_acl'),+ { type: 'host', id: '3rd:sandbox-recipes/plugin-a' },+ { isShare: false }+ )+ ).rejects.toMatchObject({ status: 403, code: 'agent_manager_forbidden' })+ })+it('forbids sharing to an agent (share targets users/teams only)', async () => {const db = mockDb({ancestors: { [R]: [R] },diff --cc control-api/test/gfsHostSubject.test.tsindex 2e7973c02,c73c4206e..3afbcf71b--- a/control-api/test/gfsHostSubject.test.ts+++ b/control-api/test/gfsHostSubject.test.ts@@@ -1,4 -1,5 +1,5 @@@-import { readFileSync } from 'node:fs'import { describe, expect, it } from 'vitest'++import { readFileSync } from 'node:fs'import { makeHostSubjectId } from '../src/gfs/hostSubject.js'import { parseSubject } from '../src/routes/gfs/grants.js'diff --cc control-api/test/gfsLegacyStandaloneGrantMigration.test.tsindex 000000000,7595abf12..1cb159132mode 000000,100644..100644--- a/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts+++ b/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts@@@ -1,0 -1,234 +1,245 @@@-import { readFile } from 'node:fs/promises'+ import { describe, expect, it, vi } from 'vitest'++import { readFile } from 'node:fs/promises'+ import {+ LEGACY_STANDALONE_SUBJECT_KEY,+ applyReviewedLegacyGrantMigration,+ buildLegacyGrantMigrationReport,+ validateReviewedLegacyGrantMapping,+ } from '../src/gfs/legacyStandaloneGrantMigration.js'+ import { createGfsRouter } from '../src/routes/gfs/index.js'+ import { listLegacyStandaloneGrants } from '../src/routes/gfs/legacyStandaloneGrants.js'++ const SOURCE_ID = '10000000-0000-4000-8000-000000000001'+ const RESOURCE_ID = '20000000-0000-4000-8000-000000000001'+ const SOURCE_GRANT = {+ id: SOURCE_ID,+ drive: 'main',+ resourceId: RESOURCE_ID,+ permissions: ['write', 'read'],+ inherit: true,+ }+ const HOST_A = {+ name: 'agent-a',+ namespace: 'mcp-host',+ displayName: 'Agent A',+ active: true,+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-a' },+ }+ const HOST_B = {+ name: 'agent-b',+ namespace: 'mcp-host',+ displayName: 'Agent B',+ active: true,+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-b' },+ }++ function makeApi(hosts = [HOST_A, HOST_B]) {+ return {+ getLegacyGrants: vi.fn(async () => ({+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,+ grants: [SOURCE_GRANT],+ })),+ getTrustedHostDirectory: vi.fn(async () => ({ agents: hosts })),+ putGrant: vi.fn(async () => ({ ok: true, status: 200 })),+ }+ }++ async function reviewedMapping(api: ReturnType<typeof makeApi>, targets: string[]) {+ const report = await buildLegacyGrantMigrationReport(api)+ return {+ ...report.mappingTemplate,+ mappings: [{ sourceGrantId: SOURCE_ID, targets }],+ }+ }++ describe('legacy standalone GFS grant migration', () => {+ it('registers the authenticated legacy inventory endpoint exactly once', () => {+ const router = createGfsRouter() as unknown as {+ stack: Array<{ route?: { path: string; methods: Record<string, boolean> } }>+ }+ 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)+ expect(registrations[0]?.route).toMatchObject({+ path: '/gfs/grants/legacy-standalone',+ methods: { get: true },+ })+ })++ it('reports deterministic legacy grants and valid candidates without inferring assignments', async () => {+ const api = makeApi([+ HOST_B,+ { ...HOST_A, active: false },+ HOST_A,+ {+ name: 'standalone',+ namespace: 'mcp-host',+ displayName: 'Standalone',+ active: true,+ gfsSubject: { type: 'host', id: '1st:mcp-host/standalone' },+ },+ ])+ 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()+ })++ it('requires an explicit exact canonical Host mapping and preserves the source row', async () => {+ const api = makeApi()+ const mapping = await reviewedMapping(api, ['host:1st:mcp-host/agent-a'])+ api.getLegacyGrants.mockClear()+ api.getTrustedHostDirectory.mockClear()++ const result = await applyReviewedLegacyGrantMigration(api, mapping)++ expect(api.getLegacyGrants).toHaveBeenCalledTimes(1)+ expect(api.getTrustedHostDirectory).toHaveBeenCalledTimes(1)+ expect(api.putGrant).toHaveBeenCalledWith({+ drive: 'main',+ resourceId: RESOURCE_ID,+ subject: { type: 'host', id: '1st:mcp-host/agent-a' },+ permissions: ['read', 'write'],+ inherit: true,+ })+ expect(result).toMatchObject({+ allApprovedIndividualGrantsSucceeded: true,+ legacyGrantsDeleted: false,+ sources: [{ legacyGrantPreserved: true, readyForRetirement: true }],+ })+ })++ it('reports partial failure and supports an idempotent retry through the same audited API', async () => {+ const api = makeApi()+ const mapping = await reviewedMapping(api, [+ 'host:1st:mcp-host/agent-a',+ 'host:1st:mcp-host/agent-b',+ ])+ let failB = true+ api.putGrant.mockImplementation(async body => ({+ ok: !(failB && JSON.stringify(body).includes('agent-b')),+ status: failB && JSON.stringify(body).includes('agent-b') ? 503 : 200,+ }))++ const first = await applyReviewedLegacyGrantMigration(api, mapping)+ expect(first.sources[0]).toMatchObject({+ legacyGrantPreserved: true,+ readyForRetirement: false,+ })+ expect(api.putGrant).toHaveBeenCalledTimes(2)++ failB = false+ api.putGrant.mockClear()+ const retry = await applyReviewedLegacyGrantMigration(api, mapping)+ expect(api.putGrant).toHaveBeenCalledTimes(2)+ expect(retry).toMatchObject({+ allApprovedIndividualGrantsSucceeded: true,+ legacyGrantsDeleted: false,+ })+ })++ it('rejects a stale trusted directory before any apply request', async () => {+ const api = makeApi()+ const mapping = await reviewedMapping(api, ['host:1st:mcp-host/agent-a'])+ api.getTrustedHostDirectory.mockResolvedValue({ agents: [HOST_B] })++ await expect(applyReviewedLegacyGrantMigration(api, mapping)).rejects.toThrow(+ 'trusted_host_directory_changed'+ )+ expect(api.putGrant).not.toHaveBeenCalled()+ })++ it('rejects duplicate targets and broad or sentinel subjects', async () => {+ const api = makeApi()+ 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'+ )++ for (const target of [+ LEGACY_STANDALONE_SUBJECT_KEY,+ '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'] },+ ])+ expect(query.mock.calls[0][0]).toMatch(/^SELECT[\s\S]+WHERE subject_type = 'host'/)+ 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'")+ })++ it('rejects legacy inventory when the bounded query detects row 1001', async () => {+ const query = vi.fn(async () => ({+ rows: Array.from({ length: 1001 }, (_, index) => ({ id: String(index) })),+ }))++ await expect(listLegacyStandaloneGrants({ query })).rejects.toThrow(+ 'legacy_grant_report_limit_exceeded'+ )+ expect(query).toHaveBeenCalledWith(expect.stringContaining('LIMIT $2'), [+ '1st:mcp-host/standalone',+ 1001,+ ])+ })++ it('fails closed instead of copying or silently reducing forbidden legacy permissions', async () => {+ for (const permission of ['delete', 'manage_acl', 'share']) {+ const api = makeApi()+ api.getLegacyGrants.mockResolvedValue({+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,+ grants: [{ ...SOURCE_GRANT, permissions: ['read', permission] }],+ })++ await expect(buildLegacyGrantMigrationReport(api)).rejects.toThrow(+ 'legacy_grant_permissions_forbidden'+ )+ expect(api.putGrant).not.toHaveBeenCalled()+ }+ })+ })diff --cc control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.tsindex 000000000,55a244c1a..e234d4568mode 000000,100644..100644--- a/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts+++ b/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts@@@ -1,0 -1,139 +1,138 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest'+ import express from 'express'+ import request from 'supertest'++ // Route-level regression guard for the rate limiter on the legacy-standalone+ // grant report (CodeQL #795 fix). The limiter service itself is covered+ // elsewhere; what was untested is the WIRING — that this specific route still+ // runs the limiter, keyed per-admin on its own bucket, before doing any+ // database work. Dropping `legacyGrantReportRateLimit` from the route would+ // leave every assertion here failing rather than silently un-limiting an+ // authenticated endpoint.+ const ADMIN_SUB = vi.hoisted(() => 'admin-42')+ const mockQuery = vi.hoisted(() => vi.fn())+ const mockCheckAndIncrement = vi.hoisted(() => vi.fn())++ vi.mock('../src/db.js', () => ({+ pool: { query: (...args: unknown[]) => mockQuery(...args) },+ withTransaction: vi.fn(),+ }))++ vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: (...args: unknown[]) => mockCheckAndIncrement(...args),+ }))++ // Mirrors the real middleware's contract: it authenticates and publishes the+ // admin claims on the request. The limiter keys on `adminAuth.sub`, so the+ // stub must populate it exactly like `requireAuthForControlUI` does.+ vi.mock('../src/middleware/controlUIAuth.js', () => ({+ requireAuthForControlUI: (+ req: express.Request,+ res: express.Response,+ next: express.NextFunction+ ) => {+ if (req.header('x-test-auth') !== 'operator') {+ res.status(401).json({ error: 'Unauthorized' })+ return+ }+ ;(req as express.Request & { adminAuth?: { sub: string } }).adminAuth = { sub: ADMIN_SUB }+ next()+ },+ }))++ const RESOURCE_ID = '20000000-0000-4000-8000-000000000001'++ function allowed(remaining = 29) {+ return {+ allowed: true,+ remaining,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 30 - remaining,+ }+ }++ function denied() {+ return {+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 30_000,+ windowStartMs: Date.now(),+ count: 31,+ }+ }++ 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()+ app.use(express.json())+ app.use(router)+ return app+ }++ describe('GET /gfs/grants/legacy-standalone rate limiting', () => {+ beforeEach(() => {+ mockQuery.mockReset()+ mockCheckAndIncrement.mockReset()+ })++ it('serves the report and consumes its own per-admin bucket when under the limit', async () => {+ mockCheckAndIncrement.mockResolvedValue(allowed())+ mockQuery.mockResolvedValue({+ rows: [+ {+ id: '10000000-0000-4000-8000-000000000001',+ drive: 'main',+ resource_id: RESOURCE_ID,+ permissions: ['read'],+ inherit: true,+ },+ ],+ })++ const response = await request(await buildApp())+ .get('/gfs/grants/legacy-standalone')+ .set('x-test-auth', 'operator')++ // Operability: the limiter must not stand between an operator and a+ // legitimate report — the normal path still returns the inventory.+ expect(response.status).toBe(200)+ expect(response.body.grants).toHaveLength(1)+ // Wiring proof: the route consumed the DEDICATED bucket key at the+ // documented 30/min ceiling, not the grant-mutation bucket and not some+ // shared/unkeyed budget.+ expect(mockCheckAndIncrement).toHaveBeenCalledTimes(1)+ expect(mockCheckAndIncrement).toHaveBeenCalledWith(`gfsgrants-legacy:${ADMIN_SUB}`, 30)+ })++ it('returns 429 with Retry-After and never reaches the database once the bucket is exhausted', async () => {+ mockCheckAndIncrement.mockResolvedValue(denied())++ const response = await request(await buildApp())+ .get('/gfs/grants/legacy-standalone')+ .set('x-test-auth', 'operator')++ expect(response.status).toBe(429)+ expect(response.body).toMatchObject({ error: 'Too Many Requests' })+ expect(response.body.retryAfterSeconds).toBeGreaterThan(0)+ expect(response.headers['retry-after']).toBeDefined()+ expect(response.headers['x-ratelimit-limit']).toBe('30')+ expect(response.headers['x-ratelimit-remaining']).toBe('0')+ // The property that makes this a DoS control rather than a cosmetic header:+ // the request is rejected BEFORE the handler runs its Postgres query.+ expect(mockQuery).not.toHaveBeenCalled()+ })++ it('rejects unauthenticated callers before the limiter spends a token', async () => {+ const response = await request(await buildApp()).get('/gfs/grants/legacy-standalone')++ expect(response.status).toBe(401)+ // Auth precedes the limiter, so an anonymous flood cannot drain a real+ // admin's bucket (and the limiter's key is never null in practice).+ expect(mockCheckAndIncrement).not.toHaveBeenCalled()+ expect(mockQuery).not.toHaveBeenCalled()+ })+ })diff --cc control-api/test/gfsReaderRole.realPostgres.integration.test.tsindex 000000000,245b7c028..0844d4a38mode 000000,100644..100644--- a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts+++ b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts@@@ -1,0 -1,257 +1,269 @@@-import { randomBytes } from 'node:crypto'+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { randomBytes } from 'node:crypto'+ import { Pool } from 'pg'-import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'+ import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'++import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'++ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip++ function databaseUrl(baseUrl: string, database: string, user?: string, password?: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ if (user !== undefined) url.username = user+ if (password !== undefined) url.password = password+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ describeRealPostgres('GFS reader and writer login isolation', () => {+ const database = `gfs_reader_role_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ const writerPassword = randomBytes(24).toString('hex')+ const readerPassword = randomBytes(24).toString('hex')+ const inheritedRole = `gfs_drift_${randomBytes(6).toString('hex')}`+ const writerUrl = databaseUrl(connectionString, database, 'gfs_controller', writerPassword)+ const readerUrl = databaseUrl(connectionString, database, 'gfs_controller_reader', readerPassword)+ let adminPool: Pool+ let pool: Pool+ let writerPool: Pool+ let readerPool: Pool++ const readiness = (runtimePool: Pool, dsn: string, storageRole: 'writer' | 'reader') =>+ createPermissionStoreProbe({+ pool: runtimePool,+ connectionString: dsn,+ intervalMs: 0,+ storageRole,+ connectTimeoutMs: 2_000,+ })++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })++ // Match the production provisioning contract: the two runtime identities+ // 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)++ afterAll(async () => {+ await readerPool?.end()+ await writerPool?.end()+ await pool?.query('ALTER ROLE gfs_controller NOLOGIN NOINHERIT').catch(() => undefined)+ await pool?.query('ALTER ROLE gfs_controller_reader NOLOGIN NOINHERIT').catch(() => undefined)+ await pool?.query(`DROP ROLE IF EXISTS ${quoteIdent(inheritedRole)}`).catch(() => undefined)+ await pool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('authenticates distinct DSNs as the exact NOINHERIT runtime identities', async () => {+ expect(readerPassword).not.toBe(writerPassword)+ const [writerIdentity, readerIdentity, attributes] = await Promise.all([+ writerPool.query('SELECT current_user'),+ readerPool.query('SELECT current_user'),+ pool.query(+ `SELECT rolname, rolcanlogin, rolinherit+ FROM pg_roles+ WHERE rolname = ANY($1::text[])+ ORDER BY rolname`,+ [['gfs_controller', 'gfs_controller_reader']]+ ),+ ])+ expect(writerIdentity.rows[0]?.current_user).toBe('gfs_controller')+ expect(readerIdentity.rows[0]?.current_user).toBe('gfs_controller_reader')+ expect(attributes.rows).toEqual([+ { rolname: 'gfs_controller', rolcanlogin: true, rolinherit: false },+ { rolname: 'gfs_controller_reader', rolcanlogin: true, rolinherit: false },+ ])+ })++ it('repairs existing-role drift without changing LOGIN or passwords', async () => {+ await pool.query(`CREATE ROLE ${quoteIdent(inheritedRole)} NOLOGIN`)+ await pool.query(`GRANT ${quoteIdent(inheritedRole)} TO gfs_controller, gfs_controller_reader`)+ await pool.query('ALTER ROLE gfs_controller INHERIT')+ await pool.query('ALTER ROLE gfs_controller_reader INHERIT')+ await pool.query('GRANT DELETE ON gfs_resources TO gfs_controller')+ await pool.query('GRANT SELECT ON gfs_blob_manifests TO gfs_controller_reader')+ await pool.query('GRANT SELECT (email), UPDATE ON control_admin_users TO gfs_controller')+ await pool.query('GRANT SELECT (role), UPDATE ON team_members TO gfs_controller_reader')+ await pool.query('GRANT UPDATE ON SEQUENCE gfs_audit_sequence_no_seq TO gfs_controller_reader')++ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0074_gfs_runtime_role_exact_contract'+ )+ expect(migration).toBeDefined()+ await migration!.apply(pool)++ const attributes = await pool.query(+ `SELECT rolname, rolcanlogin, rolinherit, rolsuper, rolcreatedb, rolcreaterole,+ rolreplication, rolbypassrls+ FROM pg_roles+ WHERE rolname = ANY($1::text[])+ ORDER BY rolname`,+ [['gfs_controller', 'gfs_controller_reader']]+ )+ expect(attributes.rows).toEqual([+ {+ rolname: 'gfs_controller',+ rolcanlogin: true,+ rolinherit: false,+ rolsuper: false,+ rolcreatedb: false,+ rolcreaterole: false,+ rolreplication: false,+ rolbypassrls: false,+ },+ {+ rolname: 'gfs_controller_reader',+ rolcanlogin: true,+ rolinherit: false,+ rolsuper: false,+ rolcreatedb: false,+ rolcreaterole: false,+ rolreplication: false,+ rolbypassrls: false,+ },+ ])+ const memberships = await pool.query(+ `SELECT member_role.rolname+ FROM pg_auth_members membership+ JOIN pg_roles member_role ON member_role.oid = membership.member+ WHERE member_role.rolname = ANY($1::text[])`,+ [['gfs_controller', 'gfs_controller_reader']]+ )+ expect(memberships.rows).toEqual([])++ const [freshWriter, freshReader] = [+ new Pool({ connectionString: writerUrl }),+ new Pool({ connectionString: readerUrl }),+ ]+ try {+ await expect(freshWriter.query('SELECT current_user')).resolves.toMatchObject({+ rows: [{ current_user: 'gfs_controller' }],+ })+ await expect(freshReader.query('SELECT current_user')).resolves.toMatchObject({+ rows: [{ current_user: 'gfs_controller_reader' }],+ })+ } finally {+ await Promise.all([freshWriter.end(), freshReader.end()])+ }+ })++ 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 {+ await expect(readiness(readerPool, readerUrl, 'reader')()).rejects.toThrow(+ /coherence check failed|permission denied/i+ )+ } finally {+ await pool.query(restoreSql)+ }+ })++ it('cannot mutate metadata, inherit the writer, or read manifests', async () => {+ const membership = await pool.query(+ `SELECT pg_has_role('gfs_controller_reader', 'gfs_controller', 'MEMBER') AS member`+ )+ expect(membership.rows[0]?.member).toBe(false)++ const privileges = await readerPool.query(`+ SELECT+ has_table_privilege(current_user, 'gfs_resources', 'SELECT') AS can_read_resources,+ has_table_privilege(current_user, 'gfs_audit', 'INSERT') AS can_insert_audit,+ has_table_privilege(current_user, 'gfs_resources', 'INSERT') AS can_insert_resources,+ has_table_privilege(current_user, 'gfs_resources', 'UPDATE') AS can_update_resources,+ has_table_privilege(current_user, 'gfs_grants', 'INSERT') AS can_insert_grants,+ has_table_privilege(current_user, 'gfs_shares', 'INSERT') AS can_insert_shares,+ has_table_privilege(current_user, 'gfs_blob_manifests', 'SELECT') AS can_read_manifests+ `)+ expect(privileges.rows[0]).toEqual({+ can_read_resources: true,+ can_insert_audit: true,+ can_insert_resources: false,+ can_update_resources: false,+ can_insert_grants: false,+ can_insert_shares: false,+ can_read_manifests: false,+ })+ await expect(+ readerPool.query('UPDATE gfs_resources SET bytes = bytes WHERE false')+ ).rejects.toMatchObject({ code: '42501' })+ })++ it.each([+ ['writer', () => writerPool],+ ['reader', () => readerPool],+ ] as const)('%s has only the approved subject-table columns', async (_kind, runtimePool) => {+ await expect(+ runtimePool().query('SELECT id, status FROM control_admin_users WHERE false')+ ).resolves.toMatchObject({ rowCount: 0 })+ await expect(+ runtimePool().query('SELECT team_id, user_id, status FROM team_members WHERE false')+ ).resolves.toMatchObject({ rowCount: 0 })+ await expect(+ runtimePool().query('SELECT email FROM control_admin_users WHERE false')+ ).rejects.toMatchObject({ code: '42501' })+ await expect(+ runtimePool().query('SELECT role FROM team_members WHERE false')+ ).rejects.toMatchObject({ code: '42501' })+ 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 --cc control-api/test/gfsReadiness.realPostgres.integration.test.tsindex 000000000,1b676e21e..b12f2eeabmode 000000,100644..100644--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts@@@ -1,0 -1,134 +1,134 @@@-import { randomBytes } from 'node:crypto'+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { randomBytes } from 'node:crypto'+ import { Pool } from 'pg'-import { assertDbReady, initDb } from '../src/db.js'-import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'+ import type { PoolClient } from 'pg'++import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'++import { assertDbReady, initDb } from '../src/db.js'++ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip++ function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {+ const database = `gfs_readiness_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let pool: Pool++ function probeAs(client: PoolClient) {+ return createPermissionStoreProbe({+ pool: {+ connect: async () => {+ const pingClient = await pool.connect()+ return {+ query: (sql: string) => pingClient.query(sql),+ release: (error?: Error) => pingClient.release(error),+ }+ },+ },+ connectionString,+ intervalMs: 0,+ storageRole: 'writer',+ connectTimeoutMs: 2_000,+ clientFactory: () => ({+ connect: async () => undefined,+ query: (sql: string) => client.query(sql),+ end: async () => undefined,+ }),+ })+ }++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ }, 60_000)++ afterAll(async () => {+ await pool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('fails Control API readiness while the latest migration is absent', async () => {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query(+ `DELETE FROM schema_migrations WHERE version='0074_gfs_runtime_role_exact_contract'`+ )+ await expect(assertDbReady(client)).rejects.toThrow(/0074_gfs_runtime_role_exact_contract/)+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })++ it('fails GFSC readiness while the immutable blob schema is absent', async () => {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query('DROP TABLE gfs_blob_manifests')+ await client.query('SET LOCAL ROLE gfs_controller')+ await expect(probeAs(client)()).rejects.toThrow(/gfs_blob_manifests|0068/i)+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })++ it('passes GFSC writer readiness under the migrated runtime role', async () => {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query('SET LOCAL ROLE gfs_controller')+ await expect(probeAs(client)()).resolves.toBeUndefined()+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })++ it.each([+ ['resource SELECT', 'REVOKE SELECT ON gfs_resources FROM gfs_controller'],+ ['audit INSERT', 'REVOKE INSERT ON gfs_audit FROM gfs_controller'],+ ['manifest SELECT', 'REVOKE SELECT ON gfs_blob_manifests FROM gfs_controller'],+ ['manifest INSERT', 'REVOKE INSERT ON gfs_blob_manifests FROM gfs_controller'],+ ['manifest UPDATE', 'REVOKE UPDATE ON gfs_blob_manifests FROM gfs_controller'],+ ['manifest DELETE', 'REVOKE DELETE ON gfs_blob_manifests FROM gfs_controller'],+ ['resource INSERT', 'REVOKE INSERT ON gfs_resources FROM gfs_controller'],+ ['resource UPDATE', 'REVOKE UPDATE ON gfs_resources FROM gfs_controller'],+ ])('fails GFSC writer readiness without only %s', async (_name, revokeSql) => {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query(revokeSql)+ await client.query('SET LOCAL ROLE gfs_controller')+ await expect(probeAs(client)()).rejects.toThrow(+ /coherence check failed|permission denied|0068|0048/i+ )+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })+ })diff --cc control-api/test/gfsResources.routeTransaction.test.tsindex 000000000,b1f0e63a9..5d98181a6mode 000000,100644..100644--- a/control-api/test/gfsResources.routeTransaction.test.ts+++ b/control-api/test/gfsResources.routeTransaction.test.ts@@@ -1,0 -1,194 +1,222 @@@+ 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'++ const state = vi.hoisted(() => {+ const events: string[] = []+ const file = {+ resource_id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ drive: 'main',+ parent_resource_id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',+ name: 'a.md',+ kind: 'file',+ version: 2,+ deleted_at: null,+ }+ const source = {+ resource_id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',+ drive: 'main',+ parent_resource_id: null,+ name: '',+ kind: 'directory',+ version: 0,+ deleted_at: null,+ cycle: false,+ }+ const other = {+ resource_id: 'dddddddd-dddd-dddd-dddd-dddddddddddd',+ drive: 'other',+ parent_resource_id: null,+ name: '',+ kind: 'directory',+ version: 0,+ deleted_at: null,+ }+ const db = {+ query: vi.fn(async (text: string, values?: unknown[]) => {+ if (text.includes('pg_advisory_xact_lock')) {+ events.push('advisory')+ return { rows: [] }+ }+ if (text.includes('ORDER BY resource_id') && text.includes('FOR UPDATE')) {+ events.push('row-locks')+ return { rows: [] }+ }+ if (text.includes('WITH RECURSIVE chain')) return { rows: [source] }+ if (text.includes('WITH RECURSIVE subtree')) {+ events.push('paths')+ return {+ rows: [+ {+ expected_count: '1',+ updated_count: state.failPaths ? '0' : '1',+ canonical_count: '1',+ distinct_path_count: '1',+ has_cycle: false,+ },+ ],+ }+ }+ if (text.includes('UPDATE gfs_resources')) {+ events.push('mutation')+ return { rows: [{ version: 3 }] }+ }+ 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', () => ({+ withTransaction: vi.fn(async (work: (db: typeof state.db) => Promise<unknown>) => {+ state.events.push('begin')+ try {+ const result = await work(state.db)+ state.events.push('commit')+ return result+ } catch (error) {+ state.events.push('rollback')+ throw error+ }+ }),+ }))++ vi.mock('../src/middleware/controlUIAuth.js', () => ({+ requireAuthForControlUI: (_req: unknown, _res: unknown, next: () => void) => next(),+ }))++ vi.mock('../src/routes/gfs/grants.js', () => ({+ UUID_RE: /^[0-9a-f-]{36}$/,+ resolveCaller: () => ({+ isOperator: state.operator,+ subjects: new Set([state.operator ? 'operator:' : 'user:blocked']),+ actorKey: state.operator ? 'operator:' : 'user:blocked',+ }),+ driveOf: (value: unknown) => String(value),+ requestIdOf: () => 'request-1',+ checkAccess: async () => state.operator,+ auditMutation: vi.fn(async (db: unknown, params: unknown) => {+ state.auditDb = db+ state.audits.push(params)+ state.events.push('audit')+ }),+ }))+-import { handlePatch } from '../src/routes/gfs/resources.js'-+ function response() {+ return {+ code: 0,+ body: undefined as unknown,+ status(code: number) {+ this.code = code+ return this+ },+ json(body: unknown) {+ this.body = body+ return this+ },+ }+ }++ describe('gfs resource route transaction boundary', () => {+ beforeEach(() => {+ state.events.length = 0+ state.failPaths = false+ state.operator = true+ state.auditDb = undefined+ state.audits.length = 0+ state.db.query.mockClear()+ })++ 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)+ expect(state.auditDb).toBe(state.db)+ expect(state.events).toEqual([+ 'begin',+ 'advisory',+ 'row-locks',+ 'mutation',+ 'paths',+ 'audit',+ 'commit',+ ])+ })++ it('rolls back before the allowed audit when canonical path publication fails', async () => {+ state.failPaths = true+ 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(412)+ expect(state.events).toContain('rollback')+ expect(state.events).not.toContain('audit')+ expect(state.events).not.toContain('commit')+ })++ it('commits an audited authorization denial without publishing a mutation', async () => {+ state.operator = false+ 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(403)+ expect(state.events).toContain('audit')+ expect(state.events).toContain('commit')+ expect(state.events).not.toContain('mutation')+ })++ 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)+ expect(res.body).toMatchObject({ error: { code: 'cross_boundary' } })+ expect(state.audits).toHaveLength(1)+ expect(state.events).toEqual(['begin', 'advisory', 'audit', 'commit'])+ expect(state.events).not.toContain('mutation')+ })+ })diff --cc control-api/test/gfsResources.test.tsindex 81ab79e51,520e71daf..82fb92716--- a/control-api/test/gfsResources.test.ts+++ b/control-api/test/gfsResources.test.ts@@@ -5,15 -5,6 +5,7 @@@ importResourcePatchError,applyResourcePatch,} from '../src/routes/gfs/resources.js'+- /**- * P2-S05 — move/rename write path (control-api half). Drives applyResourcePatch- * with a fake GrantsDb. Acceptance: rename → write on the resource; move →- * write+delete on src parent + write on dest parent; cross-drive → cross_boundary;- * stale If-Match → precondition_failed; no escalation (a caller without the bit- * is forbidden).- */-const FILE = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'const SRC = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'const DEST = 'cccccccc-cccc-cccc-cccc-cccccccccccc'@@@ -239,6 -270,16 +271,23 @@@ describe('applyResourcePatch — concur})})+ 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',+ })+ }+ })+it('a sibling-name collision is already_exists', async () => {await expect(patch(mockDb({ update: 'conflict' }), operator, FILE, { newParentId: DEST })@@@ -248,6 -289,34 +297,36 @@@})})+ it('takes the drive advisory lock before deterministic row locks', async () => {+ 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())+ })++ it('fails closed when the source parent is tombstoned while rows are acquired', async () => {+ const db = mockDb({ afterLock: resources => (resources[SRC].deleted_at = '2026-07-17') })+ await expect(patch(db, operator, FILE, { newName: 'b.md' })).rejects.toMatchObject({+ status: 412,+ code: 'precondition_failed',+ })+ })++ it('recomputes the complete subtree path from parent/name rather than replacing text', async () => {+ const db = mockDb()+ await patch(db, operator, DIR, { newName: 'renamed' })+ const refresh = db.queries.find(query => query.text.includes('WITH RECURSIVE subtree'))+ expect(refresh?.text).toContain("parent.canonical_path || '/' || child.name")+ expect(refresh?.text).toContain('UPDATE gfs_resources resource')+ expect(refresh?.text.toLowerCase()).not.toContain('replace(')+ expect(refresh?.values).toEqual(['main', DIR, '/renamed'])+ })+it('a no-op patch is path_invalid', async () => {await expect(patch(mockDb(), operator, FILE, {})).rejects.toBeInstanceOf(ResourcePatchError)})diff --cc control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.tsindex 000000000,09a5fb963..8b09d1728mode 000000,100644..100644--- a/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts+++ b/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts@@@ -1,0 -1,349 +1,384 @@@+ 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 {- GfsWriteService,+ type BlobWriter,++ GfsWriteService,+ 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_URL+ const describeRealPostgres = adminUrl ? describe : describe.skip+ const operator: GfsCaller = {+ isOperator: true,+ subjects: new Set(['operator:']),+ actorKey: 'operator:',+ }++ function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+ }++ function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+ }++ async function begin(client: PoolClient): Promise<void> {+ await client.query('BEGIN')+ await client.query(`SET LOCAL lock_timeout = '5s'`)+ await client.query(`SET LOCAL statement_timeout = '10s'`)+ }++ async function waitUntilBlocked(+ pool: Pool,+ blockedPid: number,+ blockerPid: number,+ label: string+ ): Promise<void> {+ const deadline = Date.now() + 5_000+ while (Date.now() < deadline) {+ const result = await pool.query<{ blocked: boolean }>(+ `SELECT $2::integer = ANY(pg_blocking_pids($1::integer)) AS blocked`,+ [blockedPid, blockerPid]+ )+ if (result.rows[0]?.blocked) return+ await new Promise<void>(resolve => setImmediate(resolve))+ }+ throw new Error(`${label}: expected PostgreSQL blocker was not observed`)+ }++ interface Tree {+ drive: string+ root: string+ source: string+ destinationA: string+ destinationB: string+ child: string+ }++ async function seedTree(pool: Pool, label: string): Promise<Tree> {+ const tree: Tree = {+ drive: `real-pg-${label}-${randomBytes(4).toString('hex')}`,+ root: randomUUID(),+ source: randomUUID(),+ destinationA: randomUUID(),+ destinationB: randomUUID(),+ child: randomUUID(),+ }+ await pool.query(+ `INSERT INTO gfs_resources+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes)+ VALUES ($1,$6,NULL,'','directory','/',0,0),+ ($2,$6,$1,'source','directory','/source',0,0),+ ($3,$6,$1,'destination-a','directory','/destination-a',0,0),+ ($4,$6,$1,'destination-b','directory','/destination-b',0,0),+ ($5,$6,$2,'child.txt','file','/source/child.txt',0,0)`,+ [tree.root, tree.source, tree.destinationA, tree.destinationB, tree.child, tree.drive]+ )+ return tree+ }++ async function move(client: PoolClient, tree: Tree, destination: string): Promise<number> {+ const result = await applyResourcePatch(+ client,+ operator,+ tree.drive,+ tree.child,+ { newParentId: destination },+ async () => undefined+ )+ return result.version+ }++ const blobs: BlobWriter = {+ async writeImmutable(resourceId: string, generation: string, data: Readable | Buffer) {+ if (!Buffer.isBuffer(data)) throw new Error('real-PG fixture expects buffered replacement')+ return {+ blobKey: `${resourceId.replaceAll('-', '')}/${generation}`,+ bytes: data.length,+ contentSha256: createHash('sha256').update(data).digest('hex'),+ }+ },+ async verify() {},+ async deleteByKey() {},+ async deleteLegacyFlat() {},+ }++ function boundTransaction(client: PoolClient): Transactor {+ return { transaction: work => work(client) }+ }+ function writer(client: PoolClient, manifests = new PgBlobStagingStore(client)): GfsWriteService {+ return new GfsWriteService(boundTransaction(client), blobs, manifests)+ }+ 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> {+ const result = await pool.query<{ violations: string }>(`WITH RECURSIVE ancestry AS (+ SELECT resource_id AS live_id,parent_resource_id,ARRAY[resource_id]::uuid[] visited+ FROM gfs_resources WHERE deleted_at IS NULL UNION ALL+ SELECT a.live_id,p.parent_resource_id,a.visited||p.resource_id FROM ancestry a+ JOIN gfs_resources p ON p.resource_id=a.parent_resource_id+ WHERE NOT p.resource_id=ANY(a.visited))+ SELECT count(*) violations FROM ancestry a JOIN gfs_resources p+ ON p.resource_id=a.parent_resource_id WHERE p.deleted_at IS NOT NULL`)+ expect(Number(result.rows[0]?.violations)).toBe(0)+ }++ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {+ const database = `gfs_phase0_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let pool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ }, 60_000)++ afterAll(async () => {+ await pool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('serializes create/delete and makes delete observe the committed child', async () => {+ const tree = await seedTree(pool, 'create-delete')+ const creator = await pool.connect()+ const deleter = await pool.connect()+ try {+ await Promise.all([begin(creator), begin(deleter)])+ const creatorPid = Number((await creator.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)+ const deleterPid = Number((await deleter.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)+ await writer(creator).create({+ drive: tree.drive,+ parentId: tree.destinationA,+ 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' })+ await deleter.query('ROLLBACK')+ } finally {+ await creator.query('ROLLBACK').catch(() => undefined)+ await deleter.query('ROLLBACK').catch(() => undefined)+ for (const client of [creator, deleter]) client.release()+ }+ await expectNoLiveNodeBelowTombstone(pool)+ }, 20_000)++ it('serializes move/delete and prevents a half-observed destination', async () => {+ const tree = await seedTree(pool, 'move-delete')+ const [mover, deleter] = await Promise.all([pool.connect(), pool.connect()])+ try {+ await Promise.all([begin(mover), begin(deleter)])+ 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' })+ await deleter.query('ROLLBACK')+ } finally {+ await mover.query('ROLLBACK').catch(() => undefined)+ await deleter.query('ROLLBACK').catch(() => undefined)+ for (const client of [mover, deleter]) client.release()+ }+ await expectNoLiveNodeBelowTombstone(pool)+ }, 20_000)++ 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 () => {+ const tree = await seedTree(pool, 'subtree-paths')+ const [nested, leaf] = [randomUUID(), randomUUID()]+ await pool.query(+ `INSERT INTO gfs_resources+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes)+ VALUES ($1,$3,$4,'nested','directory','/source/nested',0,0),+ ($2,$3,$1,'leaf.txt','file','/source/nested/leaf.txt',0,0)`,+ [nested, leaf, tree.drive, tree.source]+ )+ const client = await pool.connect()+ try {+ await begin(client)+ await applyResourcePatch(- client, operator, tree.drive, tree.source, { newParentId: tree.destinationA }, async () => undefined++ 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]]+ )- 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' },+ { name: 'nested', path_cache: '/destination-a/source/nested' },+ { name: 'leaf.txt', path_cache: '/destination-a/source/nested/leaf.txt' },+ ])+ })++ it('serializes two moves and leaves one coherent final parent and path', async () => {+ const tree = await seedTree(pool, 'move-move')+ const [first, second] = await Promise.all([pool.connect(), pool.connect()])+ try {+ await Promise.all([begin(first), begin(second)])+ const firstPid = Number((await first.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)+ const secondPid = Number((await second.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)+ expect(await move(first, tree, tree.destinationA)).toBe(1)+ const secondMove = move(second, tree, tree.destinationB)+ await waitUntilBlocked(pool, secondPid, firstPid, 'move/move')+ await first.query('COMMIT')+ await expect(secondMove).resolves.toBe(2)+ await second.query('COMMIT')+ const final = await pool.query(+ `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)+ for (const client of [first, second]) client.release()+ }+ }, 20_000)++ it('never lets cleanup claim a generation while publication holds its row lock', async () => {+ const tree = await seedTree(pool, 'publish-cleanup')+ const [publisher, cleanup] = await Promise.all([pool.connect(), pool.connect()])+ const paused = deferred()+ const resume = deferred()+ try {+ await begin(cleanup)+ const transactor: Transactor = {+ transaction: async work => {+ await begin(publisher)+ const result = await work(publisher)+ paused.resolve()+ await resume.promise+ await publisher.query('COMMIT')+ return result+ },+ }+ const manifests = new PgBlobStagingStore(pool)+ const replacement = new GfsWriteService(transactor, blobs, manifests).replace({+ drive: tree.drive,+ resourceId: tree.child,+ ifMatch: 0,+ content: Buffer.from('replacement'),+ })+ await paused.promise+ const store = new PgBlobStagingStore(cleanup)+ await expect(store.claimExpiredCandidate(0)).resolves.toBeNull()+ resume.resolve()+ const published = await replacement+ const row = await pool.query<{ blob_key: string | null }>(+ 'SELECT blob_key FROM gfs_resources WHERE resource_id=$1',+ [tree.child]+ )+ expect(row.rows[0]?.blob_key).toBe(published.blobKey)+ await cleanup.query('ROLLBACK')+ } finally {+ await publisher.query('ROLLBACK').catch(() => undefined)+ await cleanup.query('ROLLBACK').catch(() => undefined)+ for (const client of [publisher, cleanup]) client.release()+ }+ }, 20_000)+ })diff --cc control-api/test/routes.overview.test.tsindex 538f0edb9,797dff7fc..289cbf827--- a/control-api/test/routes.overview.test.ts+++ b/control-api/test/routes.overview.test.ts@@@ -1,86 -1,135 +1,136 @@@--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");++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')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 singleRes = await request(app).get("/admin/hosts/host-a/overview").expect(200);- expect(singleRes.body.host.metadata.name).toBe("host-a");- });- 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 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");- });++ 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 --cc control-api/test/routes.profileAdmin.test.tsindex 046af7f57,483b6a66e..88262e5eb--- a/control-api/test/routes.profileAdmin.test.ts+++ b/control-api/test/routes.profileAdmin.test.ts@@@ -200,7 -200,7 +200,9 @@@ describe('routes/profileAdmin', () =>return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]}if (plural === 'hosts') {- return [{ metadata: { name: 'agent-live' }, spec: { enabled: false } }]- return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]++ return [++ { metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } },++ ]}return []})@@@ -243,7 -243,7 +245,9 @@@return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]}if (plural === 'hosts') {- return [{ metadata: { name: 'agent-live' }, spec: { enabled: false } }]- return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]++ return [++ { metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } },++ ]}return []})diff --cc control-ui/components/__tests__/GovernedTraceSurface.test.tsxindex d936f52be,97b8e7025..1a984cab3--- a/control-ui/components/__tests__/GovernedTraceSurface.test.tsx+++ b/control-ui/components/__tests__/GovernedTraceSurface.test.tsx@@@ -1,6 -1,6 +1,7 @@@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,diff --cc control-ui/e2e/host-stateless-channel-rejection.spec.tsindex 000000000,ecf8655fe..3467625f3mode 000000,100644..100644--- a/control-ui/e2e/host-stateless-channel-rejection.spec.ts+++ b/control-ui/e2e/host-stateless-channel-rejection.spec.ts@@@ -1,0 -1,229 +1,232 @@@+ /**+ * E2E -- Operator visibility: stateless × CommunicationChannel hard-rejection banner+ *+ * Validates plan Addendum 6 item 4 (issue #791) on the LIVE control-ui host detail+ * view: a stateless Host that has a CONFIRMED CommunicationChannel association is+ * hard-rejected by HCC (effectiveMode=stateful + StatelessEnableRejected condition),+ * and the operator sees a prominent warning banner carrying the status reason+ * VERBATIM plus the disassociation recovery action. Removing the channel clears it.+ *+ * Why this spec arranges via a direct CRD write (kubectl), not the control-api:+ * The normal control-api/UI path CANNOT reach this state by design — control-api+ * rejects associating a CommunicationChannel with a stateless Host, and rejects+ * flipping a channel-bound Host to stateless, both with 409+ * `stateless_host_communication_channel_conflict`+ * (control-api/src/routes/admin/resources.ts). The hard-rejection is HCC's+ * defensive backstop for direct/racing CRD writes (AP-7,+ * docs/architecture/stateless-invariants.md). So this spec reproduces exactly that+ * race: it `kubectl apply`s a CommunicationChannel referencing a dedicated stateless+ * Host, then asserts the operator-facing banner.+ *+ * Opt-in: this spec is skipped unless E2E_STATELESS_CHANNEL_REJECTION=1, because it+ * requires a dedicated stateless Host and a kubectl context.+ *+ * KNOWN RED in this repository, for a reason unrelated to the executor fix: the+ * assertion below reads `status.lifecycle.effectiveMode`, which is NOT part of this+ * repo's HostLifecycleStatus (see host-context-controller/src/types.ts) and is never+ * written by this tree's HCC. The channel hard-rejection itself DOES work here — it is+ * observable through the StatelessEnableRejected condition, the stateful pod template,+ * and the banner text — but this spec will fail on the effectiveMode token until the+ * upstream hostLifecycleDecision model is ported. Do not weaken the assertion to make+ * it pass; port the model, or assert on the condition instead.+ *+ * Prerequisites (when enabled):+ * 1. Port-forwards running (control-ui :3000, control-api :8090).+ * 2. Admin credentials: ADMIN_USER, ADMIN_PASS.+ * 3. E2E_STATELESS_HOST — a dedicated Host with spec.lifecycle.stateless=true that is+ * NOT chatllm-stateless (avoids colliding with the transient Test 2d window of+ * scripts/e2e/e2e-stateless-suspend-wake.sh on a shared profile).+ * 4. E2E_KUBECONTEXT (or CONTEXT) — an allowed kubectl context (clerum-test /+ * clerum-codex-* / gke_<project>_<zone>_<cluster>). Passed to every kubectl call.+ */-import { execFileSync } from 'node:child_process'+ import { type Page, expect, test } from '@playwright/test'++import { execFileSync } from 'node:child_process'++ const BASE_UI = process.env.CONTROL_UI_URL || 'http://localhost:3000'+ const ADMIN_USER = process.env.ADMIN_USER || 'admin'+ const ADMIN_PASS = process.env.ADMIN_PASS || 'admin123!'++ const ENABLED = process.env.E2E_STATELESS_CHANNEL_REJECTION === '1'+ const HOST = process.env.E2E_STATELESS_HOST || ''+ const KUBECONTEXT = process.env.E2E_KUBECONTEXT || process.env.CONTEXT || ''+ const HOSTS_NS = process.env.E2E_HOSTS_NAMESPACE || 'mcp-host'+ const CHANNELS_NS = process.env.E2E_CHANNELS_NAMESPACE || 'channels'+ const REJECTED_CONDITION = 'StatelessEnableRejected'++ // Unique per run so parallel/leftover runs never collide, and cleanup is targeted.+ const CC_NAME = `e2e-vis-stateless-reject-${Date.now()}`++ function kubectl(args: string[], input?: string): string {+ if (!KUBECONTEXT) {+ throw new Error(+ 'E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context; kubectl context is never inferred.'+ )+ }+ return execFileSync('kubectl', ['--context', KUBECONTEXT, ...args], {+ encoding: 'utf8',+ ...(input !== undefined ? { input } : {}),+ })+ }++ function getHostJson(): {+ effectiveMode?: string+ rejected?: boolean+ rejectionMessage?: string+ } {+ const raw = kubectl(['get', 'host', HOST, '-n', HOSTS_NS, '-o', 'json'])+ const obj = JSON.parse(raw) as {+ status?: {+ lifecycle?: { effectiveMode?: string }+ conditions?: Array<{ type?: string; status?: string; message?: string }>+ }+ }+ const condition = obj.status?.conditions?.find(c => c.type === REJECTED_CONDITION)+ return {+ effectiveMode: obj.status?.lifecycle?.effectiveMode,+ rejected: condition?.status === 'True',+ rejectionMessage: condition?.message,+ }+ }++ function applyChannel(): void {+ const manifest = `apiVersion: clerum.io/v1alpha1+ kind: CommunicationChannel+ metadata:+ name: ${CC_NAME}+ namespace: ${CHANNELS_NS}+ spec:+ hostRef: ${HOST}+ email:+ - channelId: "INBOX"+ emails:+ - "[email protected]"+ `+ kubectl(['apply', '-n', CHANNELS_NS, '-f', '-'], manifest)+ }++ function deleteChannel(): void {+ try {+ kubectl(['delete', 'communicationchannel', CC_NAME, '-n', CHANNELS_NS, '--ignore-not-found'])+ } catch (err) {+ // Cleanup is best-effort; surface it but never mask a prior assertion failure.+ console.warn(`[e2e] failed to delete CommunicationChannel ${CC_NAME}: ${String(err)}`)+ }+ }++ async function login(page: Page) {+ await page.goto(BASE_UI)+ await page.waitForSelector('text=Sign in', { timeout: 15_000 })+ const inputs = page.locator('input')+ await inputs.nth(0).fill(ADMIN_USER)+ await inputs.nth(1).fill(ADMIN_PASS)+ await page.locator('button:has-text("Sign in")').last().click()+ await page.waitForSelector('text=Marketplace', { timeout: 20_000 })+ }++ test.describe('operator sees the stateless × CommunicationChannel hard-rejection banner', () => {+ test.skip(+ !ENABLED,+ 'opt-in: set E2E_STATELESS_CHANNEL_REJECTION=1 (with E2E_STATELESS_HOST, E2E_KUBECONTEXT) and deploy the Addendum-6 executor fix'+ )++ test.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([+ 'get',+ 'host',+ HOST,+ '-n',+ HOSTS_NS,+ '-o',+ 'jsonpath={.spec.lifecycle.stateless}',+ ]).trim()+ if (statelessRaw !== 'true') {+ throw new Error(+ `E2E_STATELESS_HOST "${HOST}" must have spec.lifecycle.stateless=true (got "${statelessRaw}"). Host status: ${JSON.stringify(host)}`+ )+ }+ // Ensure a clean slate from any aborted prior run.+ deleteChannel()+ })++ test.afterAll(() => {+ deleteChannel()+ })++ test('renders the hard-rejection warning verbatim and clears it after disassociation', async ({+ page,+ }) => {+ // Arrange: the AP-7 racing CRD write — associate a channel with the stateless Host.+ applyChannel()++ // HCC hard-rejects on the next reconcile: effectiveMode=stateful + rejected condition.+ // Bounded, fail-loud poll — on timeout the last observed status is reported.+ await expect+ .poll(() => JSON.stringify(getHostJson()), {+ timeout: 120_000,+ intervals: [2_000],+ message:+ '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().rejectionMessage+ expect(rejectionMessage, 'StatelessEnableRejected condition must carry a message').toBeTruthy()+ // Contract (Addendum 6): the message names the channel count AND the recovery action.+ expect(rejectionMessage).toMatch(/disassociate/i)++ // Assert the operator-facing banner shows the status message VERBATIM.+ // The verbatim reason renders on TWO deliberate operator-visibility surfaces —+ // the warning banner AND the lifecycle chip — so scope each assertion to its+ // own surface rather than letting an unscoped getByText(reason) collide across+ // both (strict-mode violation).+ await login(page)+ await page.goto(`${BASE_UI}/hosts/${encodeURIComponent(HOST)}`)+ // Anchor on the banner CONTAINER, not the 'Stateless mode rejected:' text —+ // that phrase lives in a <strong> leaf whose text is only the prefix, so the+ // reason (a sibling text node in the same .cu-banner--warning div) is not part+ // of the leaf. Match the container by class + its heading text, then assert+ // the reason WITHIN it.+ const rejectionBanner = page.locator('.cu-banner--warning', {+ hasText: 'Stateless mode rejected:',+ })+ await expect(rejectionBanner).toBeVisible({ timeout: 20_000 })+ // (1) the warning banner container carries the reason verbatim+ await 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 here+ // fails the test loudly instead of being swallowed mid-scenario.+ kubectl(['delete', 'communicationchannel', CC_NAME, '-n', CHANNELS_NS, '--ignore-not-found'])+ await expect+ .poll(() => JSON.stringify(getHostJson()), {+ timeout: 120_000,+ intervals: [2_000],+ message: 'HCC did not clear the hard-rejection after the CommunicationChannel was removed.',+ })+ .toMatch(/"rejected":false/)++ // BOTH surfaces must clear once the Host reports stateless-active again: the+ // warning banner disappears AND the rejection reason no longer renders on any+ // surface (banner or lifecycle chip).+ await page.reload()+ await expect(+ page.locator('.cu-banner--warning', { hasText: 'Stateless mode rejected:' })+ ).toHaveCount(0, { timeout: 20_000 })+ await expect(page.getByText(rejectionMessage as string, { exact: false })).toHaveCount(0, {+ timeout: 20_000,+ })+ })+ })diff --cc desktop-app/src/__tests__/appService.gfs.test.tsindex a3955c0ad,7670eaa97..c0dc1fd0b--- a/desktop-app/src/__tests__/appService.gfs.test.ts+++ b/desktop-app/src/__tests__/appService.gfs.test.ts@@@ -65,11 -91,11 +91,11 @@@ describe('AppService GFS delegation subasync subjectKey => {const service = gfsService()- await expect(service.grantGfs(RESOURCE_ID, subjectKey, ['read'], 'main')).rejects.toThrow(- 'subject must be user:<id> or team:<id>'- 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> or team:<id>'+ await expect(service.createGfsShare(RESOURCE_ID, [subjectKey], 'main')).rejects.toThrow(+ 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>')expect(service.gfsClient.grant).not.toHaveBeenCalled()diff --cc desktop-app/test/e2e-playwright/gfs-agent-copy.test.tsindex 000000000,d00cfa1b7..47a40cc34mode 000000,100644..100644--- a/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts@@@ -1,0 -1,462 +1,485 @@@+ /**+ * Issue #797 T2: real Desktop login -> exact Agent A -> native Copy/Rename ->+ * exact Agent B denial -> audited revoke -> same-runtime Agent A denial.+ * SQL/PVC and grant operations are named preconditions/assertions only; no+ * 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,+ countGfsLiveChildrenByName,+ getGfsChildResourceSummary,+ getGfsTreeAclShareCounts,+ getGfsTreeAclShareRows,+ getGfsTreeSnapshot,+ gfsGrantRevokeAuditCount,+ revokeGfsGrantViaControlApi,+ seedAgentGfsCopyFixtures,+ } from './helpers/gfsFixtures'-import { exactNameFilter } from './helpers/agentLocators'-import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'+ import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'+ import { launchAndLogin } from './workflowUi'++ const OWNER_EMAIL = '[email protected]'+ // Multi-tool turns (rename + recursive list + read-every-file) on the local+ // glm profile routinely exceed the 180s single-turn calibration.+ const RESPONSE_TIMEOUT_MS = 300_000+ const SENSITIVE_OUTPUT =+ /\/data\/gfs|\/mnt\/|\.generations|blob_key|blobKey|\bSQL\b|internal (?:path|error)|stack trace/i++ async function openExactAgent(+ page: Page,+ agentName: string,+ opts: { reuseThread?: boolean } = {}+ ): Promise<void> {+ await openAgentsPage(page)+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible()+ const row = page.getByLabel(`Open details for ${agentName}`, { exact: true })+ await expect(row).toBeVisible({ timeout: 30_000 })+ await row.click()+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible({ timeout: 15_000 })+ await page.getByTestId('nav-chat').click()+ await expect(page.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })+ // Starting a new chat can reset the composer to the DEFAULT agent, so it+ // must happen BEFORE the agent switch — never after, or the turn silently+ // goes to the wrong agent.+ if (!opts.reuseThread) {+ const fresh = page.getByRole('button', { name: /new (?:chat|thread)/i }).first()+ if (await fresh.isVisible().catch(() => false)) await fresh.click()+ }+ // The product binds the composer to an agent ONLY through the chat view's+ // "Switch chat agent" selector — opening another agent's details page+ // deliberately does not switch the chat. Drive exactly that user flow.+ const switcher = page.getByRole('button', { name: 'Switch chat agent' })+ const boundSwitcher = switcher.filter(exactNameFilter(agentName))+ 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()+ }+ // A stateless agent suspended at idle wakes through the rpc-proxy+ // wake-and-hold path (up to ~90s of scale-up) before its chat shell binds;+ // the binding element itself remains mandatory and is the LAST gate before+ // any turn is sent.+ await expect(boundSwitcher.or(breadcrumb).first()).toBeVisible({ timeout: 120_000 })+ if (opts.reuseThread) {+ // reuseThread continues the agent's MOST-RECENT session. Callers must drive+ // purely by visible NAMES here (never resource identifiers), because which+ // of the agent's threads is most-recent is not guaranteed: any earlier step+ // that opens a fresh thread for this agent becomes the newest one, so the+ // reused prompt must not presume a specific prior conversation history.+ await page.locator('.agent-dedicated-session-title-btn').first().click()+ await expect(page.getByTestId('agent-response').first()).toBeVisible({ timeout: 15_000 })+ } else {+ await expect(page.getByTestId('agent-response')).toHaveCount(0, { timeout: 10_000 })+ }+ }++ async function sendAgentTurn(page: Page, prompt: string): Promise<Locator> {+ const responseIndex = await page.getByTestId('agent-response').count()+ const approvalIndex = await page.getByTestId('approval-approve-btn').count()+ const progressIndex = await page.getByTestId('progress-expand-btn').count()+ await expect(page.getByTestId('chat-input')).toBeEnabled()+ await page.getByTestId('chat-input').fill(prompt)+ await page.getByTestId('send-button').click()++ const response = page.getByTestId('agent-response').nth(responseIndex)+ const retrySend = page.getByRole('button', { name: 'Retry last send' })+ let approvals = 0+ let sendRetries = 0+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS+ for (;;) {+ const remaining = deadline - Date.now()+ if (remaining <= 0) throw new Error('timed out waiting for the issue #797 agent turn')+ // A just-restarted runtime can drop the send with a visible "Temporary+ // connection issue" banner; a real user presses the product's own+ // "Retry last send". Bounded — a persistent failure still fails the turn.+ if (await retrySend.isVisible().catch(() => false)) {+ if (sendRetries >= 3) throw new Error('agent send kept failing after 3 product retries')+ sendRetries += 1+ // An absorbed retry must be LOUD in a green run: warn on the console+ // and annotate the test report, without changing pass/fail semantics.+ const turnLabel = prompt.slice(0, 80)+ 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+ }+ const approval = page.getByTestId('approval-approve-btn').nth(approvalIndex + approvals)+ const approvalWait = approval+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })+ .then(() => 'approval' as const)+ const responseWait = response+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })+ .then(() => 'response' as const)+ // The losing waitFor keeps its timer; silence its eventual rejection so a+ // settled turn cannot surface a late "Target closed" unhandled rejection.+ // .catch() returns a NEW promise, so the originals still race unchanged.+ void approvalWait.catch(() => undefined)+ void responseWait.catch(() => undefined)+ let visible: 'approval' | 'response'+ try {+ visible = await Promise.race([approvalWait, responseWait])+ } catch {+ // Neither appeared within this slice; loop to re-check the retry banner+ // and the overall deadline.+ continue+ }+ if (visible === 'response') break+ await approval.click()+ approvals += 1+ }+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })+ const expand = page.getByTestId('progress-expand-btn').nth(progressIndex)+ await expect(expand).toBeVisible({ timeout: 30_000 })+ await expand.click()+ return expand.locator('..')+ }++ function toolRow(stepper: Locator, name: string): Locator {+ return stepper.locator('.stepper-step').filter({ hasText: name }).last()+ }++ async function expectToolSuccess(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')).toHaveCount(0)+ }++ async function expectToolForbidden(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 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)+ }++ async function expectToolConflict(stepper: Locator, name: string): Promise<void> {+ // A copy onto an existing name is a non-destructive conflict: gfsc maps+ // already_exists to 409, which mcp-host redacts to `gfsc 409: conflict`.+ // It must never read as a 503/not_mounted infra failure and must never leak+ // server internals.+ 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)+ }++ async function expectCopyPublicOutput(stepper: Locator): Promise<void> {+ // The step-output panel renders the mcp-host preview, which truncates each+ // line at 200 chars (toolUseLoopPreviews MAX_LINE_LENGTH) — a single-line+ // copy JSON is cut after ok/requestId/resourceId/gfsUri. Those visible+ // fields are asserted here; name and object/file/folder counts are business+ // signals proven from the database right after each copy (child-by-name+ // lookup plus full tree-snapshot equality), where truncation cannot hide a+ // wrong result.+ const row = toolRow(stepper, 'gfs_copy')+ await row.click()+ const output = row+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')+ .locator('.stepper-step-output-code')+ await expect(output).toBeVisible({ timeout: 10_000 })+ await expect(output).toContainText('"ok":true')+ await expect(output).toContainText('"requestId":')+ await expect(output).toContainText('"resourceId":')+ await expect(output).toContainText('"gfsUri":"gfs://main/')+ await expect(output).not.toContainText(SENSITIVE_OUTPUT)+ }++ 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> {+ await openResourcesNavItem(page, 'nav-files')+ const browser = page.getByRole('region', { name: 'Global File System browser' })+ await expect(browser).toBeVisible({ timeout: 20_000 })+ return browser+ }++ async function browseSourceTree(page: Page, fixtures: AgentGfsCopyFixtures): Promise<void> {+ const browser = await openFilesBrowser(page)+ await browser.getByRole('button', { name: fixtures.tree.sourceName, exact: true }).click()+ await expect(+ browser.getByRole('button', { name: fixtures.tree.standaloneFileName, exact: true })+ ).toBeVisible()+ await browser.getByRole('button', { name: 'nested', exact: true }).click()+ await expect(browser.getByRole('button', { name: 'alpha.txt', exact: true })).toBeVisible()+ await browser.getByRole('button', { name: 'empty', exact: true }).click()+ await expect(browser.getByText('This folder is empty', { exact: true })).toBeVisible()+ }++ async 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()+ await expect(browser.getByRole('button', { name: 'alpha.txt', exact: true })).toBeVisible()+ await expect(browser.getByRole('button', { name: 'deeper', exact: true })).toBeVisible()+ await browser.getByRole('button', { name: 'empty', exact: true }).click()+ await expect(browser.getByText('This folder is empty', { exact: true })).toBeVisible()+ }++ test.describe('GFS per-agent native Copy and immediate grant enforcement (issue #797)', () => {+ test.describe.configure({ mode: 'serial' })+ let fixtures: AgentGfsCopyFixtures++ test.beforeAll(() => {+ assertGfsInfraHealthy()+ fixtures = seedAgentGfsCopyFixtures(OWNER_EMAIL)+ })++ test.afterAll(() => fixtures?.cleanup())++ test('copies complete trees and revokes destination access in one runtime', async ({}, testInfo) => {+ // Four real LLM turns (each allowed RESPONSE_TIMEOUT_MS) plus Electron+ // login and two Files-tree walks cannot fit the 240s config default.+ testInfo.setTimeout(1_200_000)+ const sourceBefore = getGfsTreeSnapshot(fixtures.tree.sourceResourceId)+ const sourceAclShareBefore = getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)+ const sourceAclShareRecords = sourceAclShareBefore.map(+ row => JSON.parse(row) as { kind: 'grant' | 'share'; row: Record<string, unknown> }+ )+ expect(+ sourceAclShareRecords.filter(+ record =>+ record.kind === 'share' &&+ record.row.id === fixtures.sourceShareId &&+ record.row.subject_id === fixtures.sourceShareSubjectId+ )+ ).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 () => {+ await browseSourceTree(page, fixtures)+ await openExactAgent(page, fixtures.agentA.name)+ const steps = await sendAgentTurn(+ page,+ `In drive main, open the folder named "${fixtures.tree.sourceName}" and read the file ` ++ `"${fixtures.tree.standaloneFileName}" inside it. Then copy that file into the folder ` ++ `named "${fixtures.tree.destinationName}", naming the copy "${fixtures.fileCopyName}". ` ++ `Use only your native Clerum GFS tools; never download and re-upload content yourself.`+ )+ await expectToolSuccess(steps, 'gfs_read')+ await expectToolSuccess(steps, 'gfs_copy')+ await expectCopyPublicOutput(steps)+ const copied = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ expect(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 })+ })++ await test.step('Agent A recursively copies the complete folder', async () => {+ const steps = await sendAgentTurn(+ page,+ `Now copy the complete folder named "${fixtures.tree.sourceName}" from drive main into ` ++ `the folder named "${fixtures.tree.destinationName}", naming the copy ` ++ `"${fixtures.folderCopyName}". Make exactly one copy; do not move or delete anything.`+ )+ await expectToolSuccess(steps, 'gfs_copy')+ await expectCopyPublicOutput(steps)+ })++ await test.step('Agent A renames the copied root and reads it back', async () => {+ // A separate short turn keeps the user intent unambiguous: renaming+ // must never be "helpfully" followed by a fresh copy of the old name.+ const steps = await sendAgentTurn(+ page,+ `Rename the copy named "${fixtures.folderCopyName}" (inside ` ++ `"${fixtures.tree.destinationName}") to "${fixtures.renamedFolderName}". Then list ` ++ `that renamed folder recursively and read every file inside it. Do not copy, move, ` ++ `or delete anything.`+ )+ await expectToolSuccess(steps, 'gfs_rename')+ await expectToolSuccess(steps, 'gfs_list')+ await expectToolSuccess(steps, 'gfs_read')+ })++ await test.step('visible browse and persisted tree prove Copy did real work', async () => {+ const copied = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.renamedFolderName,+ })+ expect(copied).not.toBeNull()+ expect(+ getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.folderCopyName,+ })+ ).toBeNull()+ const copiedTree = getGfsTreeSnapshot(copied!.resourceId)+ expect(comparableTree(copiedTree)).toEqual(comparableTree(sourceBefore))+ for (const source of sourceBefore) {+ expect(copiedTree.map(node => node.resourceId)).not.toContain(source.resourceId)+ }+ expect(getGfsTreeSnapshot(fixtures.tree.sourceResourceId)).toEqual(sourceBefore)+ expect(getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)).toEqual(sourceAclShareBefore)+ expect(getGfsTreeAclShareCounts(copied!.resourceId)).toEqual({ grants: 0, shares: 0 })+ await browseDestinationTree(page, fixtures)+ })++ await test.step('copying onto an existing name is a non-destructive conflict (no duplicate)', async () => {+ // The file copy from the first step already put `fileCopyName` under the+ // destination. Copying the same source file there under the same name+ // must be refused (already_exists → gfsc 409), and — the load-bearing+ // business signal — must leave exactly one live child with that name.+ const beforeSummary = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ expect(beforeSummary).not.toBeNull()+ expect(+ countGfsLiveChildrenByName({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ ).toBe(1)+ // Fresh thread on purpose: A has no memory of the earlier copy, so it+ // must actually re-attempt the copy by name and surface the tool's real+ // result rather than answering "already done" from context.+ await openExactAgent(page, fixtures.agentA.name)+ const steps = await sendAgentTurn(+ page,+ `In drive main, copy the file "${fixtures.tree.standaloneFileName}" from the folder ` ++ `"${fixtures.tree.sourceName}" into the folder "${fixtures.tree.destinationName}", ` ++ `naming the copy "${fixtures.fileCopyName}". Use your native Clerum GFS copy tool and ` ++ `report exactly what it returns. Attempt the copy even if a listing suggests the name ` ++ `already exists — do not decline based on a prior listing — and do not rename, delete, ` ++ `or overwrite anything.`+ )+ await expectToolConflict(steps, 'gfs_copy')+ // The existing copy is untouched and NO duplicate row was created.+ const afterSummary = getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ expect(afterSummary?.resourceId).toBe(beforeSummary?.resourceId)+ expect(+ countGfsLiveChildrenByName({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.fileCopyName,+ })+ ).toBe(1)+ })++ await test.step('Agent B passes root/destination grants but unreadable child denies the tree', async () => {+ await openExactAgent(page, fixtures.agentB.name)+ const steps = await sendAgentTurn(+ page,+ `Copy the folder named "${fixtures.tree.sourceName}" from drive main into the folder ` ++ `named "${fixtures.tree.destinationName}", naming the copy "${fixtures.deniedCopyName}". ` ++ `Attempt the copy with your native Clerum GFS copy tool and report exactly what it ` ++ `returns — do not decline based on a prior listing, even if it looks like you lack access.`+ )+ await expectToolForbidden(steps, 'gfs_copy')+ expect(+ getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.deniedCopyName,+ })+ ).toBeNull()+ })++ await test.step('audited revoke denies Agent A immediately in the same runtime', async () => {+ await openExactAgent(page, fixtures.agentA.name, { reuseThread: true })+ const runtimeBefore = getManagedAgentPodIdentity(fixtures.agentA)+ const auditBefore = gfsGrantRevokeAuditCount(fixtures.agentA)+ await revokeGfsGrantViaControlApi(fixtures.destinationGrantId)+ expect(gfsGrantRevokeAuditCount(fixtures.agentA)).toBe(auditBefore + 1)+ const steps = await sendAgentTurn(+ page,+ `Copy the folder "${fixtures.tree.sourceName}" into the folder ` ++ `"${fixtures.tree.destinationName}", naming the copy ` ++ `"${fixtures.revokedCopyName}". Attempt the copy with your native Clerum GFS copy ` ++ `tool and report exactly what it returns — do not decline based on a prior listing, ` ++ `even if it looks like you lack access.`+ )+ // Under name driving, revoking the destination removes even its+ // resolvability (no-disclosure): the visible denial surfaces on the+ // agent's own discovery tool (gfsc 403/404) BEFORE any gfs_copy can be+ // issued. Require a gfsc-denied tool row, forbid any successful+ // gfs_copy, and keep the infra-shape negatives.+ const deniedGfsRow = steps+ .locator('.stepper-step-duration.state-error')+ .filter({ hasText: /gfsc 40[34]/ })+ await expect(deniedGfsRow.first()).toBeVisible({ timeout: 15_000 })+ const successfulCopy = steps+ .locator('.stepper-step')+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_copy' }) })+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })+ await expect(successfulCopy).toHaveCount(0)+ await expect(steps).not.toContainText(/gfsc 503|not_mounted/i)+ await expect(steps).not.toContainText(SENSITIVE_OUTPUT)+ // Same-runtime proof: the denial must come from live cache+ // invalidation, not from a pod restart re-reading grants.+ expect(getManagedAgentPodIdentity(fixtures.agentA)).toBe(runtimeBefore)+ expect(+ getGfsChildResourceSummary({+ parentResourceId: fixtures.tree.destinationResourceId,+ name: fixtures.revokedCopyName,+ })+ ).toBeNull()+ })++ expect(getGfsTreeSnapshot(fixtures.tree.sourceResourceId)).toEqual(sourceBefore)+ } finally {+ await app.close()+ }+ })+ })diff --cc desktop-app/test/e2e-playwright/gfs-agent-delegation.test.tsindex 000000000,612401489..951290afemode 000000,100644..100644--- a/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts@@@ -1,0 -1,798 +1,813 @@@+ /**+ * E2E — Desktop per-agent GFS delegation (plan "compressed-drifting-matsumoto",+ * ADDENDUM 1): full pre/post permission sequence with TWO agents.+ *+ * One serial suite, two serial tests sharing beforeAll fixtures:+ *+ * Test 1 — "agents have no access until granted; grant gives A read AND write":+ * 1. Pre-grant negative (chat): A, then B, asked to read the file by its+ * visible path → no-disclosure denial for BOTH (zero successful gfs_read,+ * no sentinel leak, no gfsc 503/not_mounted).+ * 2. Grant via UI: Files → Options for <folder> → Manage → Agents section →+ * select A only → read+write, inherit ON → Grant. Toast + gfs_grants row+ * (host subject = A, permissions read/write, inherit true) via SQL helper.+ * 3. Chat A read: sentinel content surfaces from the real PVC.+ * 4. Chat A write: A replaces the file content (its own tools discover+ * If-Match); new content + bumped version asserted in DB and on the PVC.+ * 5. Isolation: B (stateless — exercises the wake path) still denied.+ *+ * Test 2 — "stateless agent grant + revoke keeps agents isolated":+ * 1. Grant B via UI: second Manage round → select B → read → Grant; row+ * asserted in DB.+ * 2. Chat B read: B reads the MODIFIED sentinel (stateless runtime + fresh+ * grant proven together).+ * 3. Revoke A via UI: Manage → grants list → Revoke on A's row. Toast + row+ * deleted + gfsGrantRevokeAuditCount +1.+ * 4. Same-runtime denial for A: retry in A's existing thread is denied with+ * NO content disclosure (no successful gfs_read, no sentinel, no infra-+ * shape leak — per the name/path indistinguishability contract; a bare+ * 403/404 code is intentionally NOT asserted) and pod UID/startTime+ * invariance (no restart).+ * 5. B unaffected: B reads again — revocation is isolated in both directions.+ *+ * E2E contract (e2e-test-guardian / human-driving):+ * - Prompts and UI driving reference ONLY visible names and paths; business+ * truth is always asserted from the database and the PVC via the shared+ * SQL/kubectl helpers. No fixture helper performs the grant/revoke under+ * test — those happen exclusively through the Manage modal UI.+ * - 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 {+ type ManagedGfsAgent,+ assertGfsInfraHealthy,+ discoverManagedGfsAgents,+ 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'++ const OWNER_EMAIL = '[email protected]'+ // glm-5.1 calibration (repo baseline): single agent turns can take minutes;+ // multi-tool turns (discover + read/write) share the 300s budget proven by the+ // issue #797 copy suite.+ const RESPONSE_TIMEOUT_MS = 300_000+ const SENSITIVE_OUTPUT =+ /\/data\/gfs|\/mnt\/|\.generations|blob_key|blobKey|\bSQL\b|internal (?:path|error)|stack trace/i++ interface AgentGfsDelegationFixtures {+ /** Stateful journey agent (grantee of read+write, later revoked). */+ agentA: ManagedGfsAgent+ /** Stateless journey agent (wake path; read-only grantee, never revoked). */+ agentB: ManagedGfsAgent+ /** Seeded folder + file; the file carries the run-unique original sentinel. */+ folder: GfsFileFixture+ /** Exact content sentinel seeded into the file (PVC truth). */+ originalSentinel: string+ /** Exact replacement sentinel Agent A is asked to write in Test 1. */+ modifiedSentinel: string+ cleanup(): void+ }++ /**+ * Named setup preconditions ONLY (performed outside the journeys under test):+ * a folder+file the OWNER can see and manage. The owner grant carries+ * read+write (escalation guard: you can only grant bits you hold) and+ * manage_acl (Manage-modal delegation affordance + grants GET). NO host grant+ * is seeded — creating and revoking those is exactly what the UI journeys+ * must do themselves.+ */+ function seedAgentGfsDelegationFixtures(ownerEmail: string): AgentGfsDelegationFixtures {+ const [agentA, agentB] = discoverManagedGfsAgents()+ const folder = seedGfsFileFixture(uniqueGfsFixtureName('e2e-gfs-agent-delegation'))+ try {+ seedGfsGrant({+ resourceId: folder.resourceId,+ subjectType: 'user',+ subjectId: getE2EUserId(ownerEmail),+ permissions: ['read', 'write', 'manage_acl'],+ inherit: true,+ grantedBy: 'e2e:gfs-agent-delegation-owner',+ })+ for (const agent of [agentA, agentB]) {+ if (getGfsHostGrantsUnderTree(folder.resourceId, agent.subjectId).length !== 0) {+ throw new Error(+ `delegation fixture must start with ZERO host grants for ${agent.subjectId} — ` ++ 'the pre-grant denial phase would be meaningless'+ )+ }+ }+ return {+ agentA,+ agentB,+ folder,+ originalSentinel: `E2E GFS file fixture: ${folder.name}`,+ modifiedSentinel: `Delegated write sentinel ${folder.name} rewritten by the granted agent`,+ cleanup: () => cleanupGfsFixture(folder.name),+ }+ } catch (error) {+ try {+ cleanupGfsFixture(folder.name)+ } catch (cleanupError) {+ throw new Error(+ `GFS delegation setup failed (${String(error)}) and cleanup failed (${String(cleanupError)})`+ )+ }+ throw error+ }+ }++ async function openExactAgent(+ page: Page,+ agentName: string,+ opts: { reuseThread?: boolean } = {}+ ): Promise<void> {+ await openAgentsPage(page)+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible()+ const row = page.getByLabel(`Open details for ${agentName}`, { exact: true })+ await expect(row).toBeVisible({ timeout: 30_000 })+ await row.click()+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible({ timeout: 15_000 })+ await page.getByTestId('nav-chat').click()+ await expect(page.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })+ // Starting a new chat can reset the composer to the DEFAULT agent, so it+ // must happen BEFORE the agent switch — never after, or the turn silently+ // goes to the wrong agent.+ if (!opts.reuseThread) {+ const fresh = page.getByRole('button', { name: /new (?:chat|thread)/i }).first()+ if (await fresh.isVisible().catch(() => false)) await fresh.click()+ }+ // The product binds the composer to an agent ONLY through the chat view's+ // "Switch chat agent" selector — opening another agent's details page+ // deliberately does not switch the chat. Drive exactly that user flow.+ const switcher = page.getByRole('button', { name: 'Switch chat agent' })+ const boundSwitcher = switcher.filter(exactNameFilter(agentName))+ 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()+ }+ // A stateless agent suspended at idle wakes through the rpc-proxy+ // wake-and-hold path (up to ~90s of scale-up) before its chat shell binds;+ // the binding element itself remains mandatory and is the LAST gate before+ // any turn is sent.+ await expect(boundSwitcher.or(breadcrumb).first()).toBeVisible({ timeout: 120_000 })+ if (opts.reuseThread) {+ // The revocation retry deliberately continues the agent's most recent+ // session: the user only repeats visible paths, and any resource+ // identifiers live in the agent's own conversational memory from its+ // previous discovery.+ await page.locator('.agent-dedicated-session-title-btn').first().click()+ await expect(page.getByTestId('agent-response').first()).toBeVisible({ timeout: 15_000 })+ } else {+ await expect(page.getByTestId('agent-response')).toHaveCount(0, { timeout: 10_000 })+ }+ }++ async function sendAgentTurn(+ page: Page,+ prompt: string+ ): Promise<{ stepper: Locator; responseText: string }> {+ const responseIndex = await page.getByTestId('agent-response').count()+ const approvalIndex = await page.getByTestId('approval-approve-btn').count()+ const progressIndex = await page.getByTestId('progress-expand-btn').count()+ await expect(page.getByTestId('chat-input')).toBeEnabled()+ await page.getByTestId('chat-input').fill(prompt)+ await page.getByTestId('send-button').click()++ const response = page.getByTestId('agent-response').nth(responseIndex)+ const retrySend = page.getByRole('button', { name: 'Retry last send' })+ let approvals = 0+ let sendRetries = 0+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS+ for (;;) {+ const remaining = deadline - Date.now()+ if (remaining <= 0) throw new Error('timed out waiting for the delegation-suite agent turn')+ // A just-restarted runtime can drop the send with a visible "Temporary+ // connection issue" banner; a real user presses the product's own+ // "Retry last send". Bounded — a persistent failure still fails the turn.+ if (await retrySend.isVisible().catch(() => false)) {+ if (sendRetries >= 3) throw new Error('agent send kept failing after 3 product retries')+ sendRetries += 1+ // An absorbed retry must be LOUD in a green run: warn on the console+ // and annotate the test report, without changing pass/fail semantics.+ const turnLabel = prompt.slice(0, 80)+ console.warn(+ `[gfs-agent-delegation] "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}`,+ })+ await retrySend.click()+ continue+ }+ const approval = page.getByTestId('approval-approve-btn').nth(approvalIndex + approvals)+ const approvalWait = approval+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })+ .then(() => 'approval' as const)+ const responseWait = response+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })+ .then(() => 'response' as const)+ // The losing waitFor keeps its timer; silence its eventual rejection so a+ // settled turn cannot surface a late "Target closed" unhandled rejection.+ // .catch() returns a NEW promise, so the originals still race unchanged.+ void approvalWait.catch(() => undefined)+ void responseWait.catch(() => undefined)+ let visible: 'approval' | 'response'+ try {+ visible = await Promise.race([approvalWait, responseWait])+ } catch {+ // Neither appeared within this slice; loop to re-check the retry banner+ // and the overall deadline.+ continue+ }+ if (visible === 'response') break+ await approval.click()+ approvals += 1+ }+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })+ const responseText = (await response.textContent()) ?? ''+ const expand = page.getByTestId('progress-expand-btn').nth(progressIndex)+ await expect(expand).toBeVisible({ timeout: 30_000 })+ await expand.click()+ return { stepper: expand.locator('..'), responseText }+ }++ function toolRow(stepper: Locator, name: string): Locator {+ return stepper.locator('.stepper-step').filter({ hasText: name }).last()+ }++ async function expectToolSuccess(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')).toHaveCount(0)+ }++ /**+ * The step-output panel renders the head of the tool result payload — the+ * run-unique sentinel can only be there if gfsc actually served the file+ * content from the real PVC. The OutputPanel is a SIBLING of the step row, so+ * row→panel binds via following-sibling.+ */+ async function expectReadWithSentinel(stepper: Locator, sentinel: string): Promise<void> {+ await expectToolSuccess(stepper, 'gfs_read')+ const row = toolRow(stepper, 'gfs_read')+ await row.click()+ const output = row+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')+ .locator('.stepper-step-output-code')+ await expect(output).toBeVisible({ timeout: 10_000 })+ await expect(output).toContainText(sentinel)+ await expect(output).not.toContainText(SENSITIVE_OUTPUT)+ }++ function assertNoInfraFailureShape(responseText: string): void {+ // Credential repair must be distinguishable from resource authorization: a+ // not_mounted/503 here means the permission store broke (issue #775 shape),+ // which must NEVER read as a denial pass.+ expect(responseText.toLowerCase()).not.toContain('not_mounted')+ expect(responseText.toLowerCase()).not.toContain('gfsc 503')+ expect(responseText.toLowerCase()).not.toContain('fetch failed')+ }++ /**+ * No-disclosure denial contract for NAME/PATH driving (pattern from+ * gfs-agent-file-read.test.ts): an ungranted agent cannot even resolve the+ * resource, so a denied file is deliberately indistinguishable from an absent+ * one. The contract is: the agent really attempted its gfs tools, NO gfs_read+ * ever succeeded, nothing leaked the sentinel content, and no infra+ * 503/not_mounted shape appeared.+ */+ async function expectNoDisclosureDenial(+ turn: { stepper: Locator; responseText: string },+ forbiddenSentinels: string[]+ ): Promise<void> {+ const page = turn.stepper.page()+ assertNoInfraFailureShape(turn.responseText)+ for (const sentinel of forbiddenSentinels) {+ expect(turn.responseText).not.toContain(sentinel)+ }+ const gfsSteps = turn.stepper+ .locator('.stepper-step')+ .filter({ has: page.locator('.stepper-step-fn', { hasText: /gfs_/ }) })+ await expect(gfsSteps.first()).toBeVisible({ timeout: 15_000 })+ const successfulRead = turn.stepper+ .locator('.stepper-step')+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_read' }) })+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })+ await expect(successfulRead).toHaveCount(0)+ await expect(turn.stepper).not.toContainText(/gfsc 503|not_mounted/i)+ await expect(turn.stepper).not.toContainText(SENSITIVE_OUTPUT)+ for (const sentinel of forbiddenSentinels) {+ await expect(turn.stepper).not.toContainText(sentinel)+ }+ }++ async function openFilesBrowser(page: Page): Promise<Locator> {+ await openResourcesNavItem(page, 'nav-files')+ const browser = page.getByRole('region', { name: 'Global File System browser' })+ await expect(browser).toBeVisible({ timeout: 20_000 })+ return browser+ }++ /**+ * Enters the fixture folder (visible-path proof: the user sees the file they+ * will later name to the agents) and opens the Manage dialog through the+ * folder's own "Options for <folder>" menu.+ */+ async function openManageForFixtureFolder(+ page: Page,+ fixtures: AgentGfsDelegationFixtures+ ): Promise<Locator> {+ const browser = await openFilesBrowser(page)+ await browser.getByRole('button', { name: fixtures.folder.name, exact: true }).click()+ 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 })+ return dialog+ }++ async function closeManageDialog(page: Page, dialog: Locator): Promise<void> {+ await dialog.getByRole('button', { name: 'Close manage dialog', exact: true }).click()+ await expect(page.getByRole('dialog', { name: /^Manage folder / })).toHaveCount(0)+ }++ /**+ * Drives the Agents section of the Manage dialog exactly as a user would:+ * select ONE agent by its visible name (asserting the other stays unselected),+ * optionally add Write in the permission dropdown, keep the directory-default+ * "Include contents of this folder" toggle ON, and press Grant. Success is a+ * product toast plus the agent's row appearing in the "Who has access" list+ * (list-after-write is mandatory: the grant PUT returns no ids).+ */+ async function grantAgentAccessViaManageModal(+ page: Page,+ dialog: Locator,+ opts: { agentName: string; unselectedAgentName: string; includeWrite: boolean }+ ): Promise<void> {+ const agentSection = dialog.locator('.da-gfs-agent-access')+ await expect(agentSection).toBeVisible({ timeout: 20_000 })+ const agentGroup = agentSection.getByRole('group', { name: 'My agents' })+ await expect(agentGroup).toBeVisible({ timeout: 20_000 })+ const target = agentGroup.getByRole('button', { name: opts.agentName, exact: true })+ const untouched = agentGroup.getByRole('button', { name: opts.unselectedAgentName, exact: true })+ await expect(untouched).toBeVisible({ timeout: 20_000 })+ await target.click()+ await expect(target).toHaveAttribute('aria-pressed', 'true')+ await expect(untouched).toHaveAttribute('aria-pressed', 'false')+ if (opts.includeWrite) {+ // The agent dropdown starts at the read-only default; add Write through+ // the real menu (menuitemcheckbox), then close it by clicking the section+ // heading so the Grant press cannot be swallowed by the click-outside+ // handler.+ await agentSection.getByRole('button', { name: 'Read', exact: true }).click()+ const menu = agentSection.getByRole('menu', { name: 'Permissions' })+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Read' })).toHaveAttribute(+ 'aria-checked',+ 'true'+ )+ await menu.getByRole('menuitemcheckbox', { name: 'Write' }).click()+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Write' })).toHaveAttribute(+ 'aria-checked',+ 'true'+ )+ await agentSection.getByRole('heading', { name: 'Agents' }).click()+ await expect(+ agentSection.getByRole('button', { name: '2 permissions', exact: true })+ ).toBeVisible()+ } else {+ await expect(agentSection.getByRole('button', { name: 'Read', exact: true })).toBeVisible()+ }+ const inherit = agentSection.getByRole('checkbox', { name: 'Include contents of this folder' })+ // Directory default is ON — asserted, never toggled: a folder grant with+ // inherit=false would silently break the agent-reads-file journey.+ await expect(inherit).toBeChecked()+ await agentSection.getByRole('button', { name: 'Grant agent access', exact: true }).click()+ await expect(page.getByText('Access granted to 1 agent', { exact: true }).first()).toBeVisible({+ timeout: 20_000,+ })+ await expect(+ dialog.getByRole('button', { name: `Revoke access for ${opts.agentName}`, exact: true })+ ).toBeVisible({ timeout: 20_000 })+ }++ /**+ * Bulk multi-agent grant — the #159 feature under test (`subjects[]`). Selects+ * EVERY named agent so they are all pressed SIMULTANEOUSLY before a single+ * "Grant agent access" press, which the UI turns into ONE atomic+ * `ctrl.grant(subjects[], bits, inherit)` PUT. The plural toast ("Access+ * granted to N agents") is only emitted when the whole batch succeeds as a+ * unit, and list-after-write must then show a Revoke row for every grantee+ * (the grants GET returned all N). Read-only + directory-default inherit ON,+ * asserted, never toggled. Cardinality ≥2 is the whole point: at N=1 this path+ * is indistinguishable from the pre-#159 one-PUT-per-subject behaviour.+ */+ async function grantMultipleAgentsViaManageModal(+ page: Page,+ dialog: Locator,+ opts: { agentNames: string[] }+ ): Promise<void> {+ if (opts.agentNames.length < 2) {+ throw new Error('grantMultipleAgentsViaManageModal requires ≥2 agents to exercise subjects[]')+ }+ const agentSection = dialog.locator('.da-gfs-agent-access')+ await expect(agentSection).toBeVisible({ timeout: 20_000 })+ const agentGroup = agentSection.getByRole('group', { name: 'My agents' })+ await expect(agentGroup).toBeVisible({ timeout: 20_000 })+ // Select each agent; each toggle must stick without clearing the earlier ones.+ for (const name of opts.agentNames) {+ const target = agentGroup.getByRole('button', { name, exact: true })+ await expect(target).toBeVisible({ timeout: 20_000 })+ await target.click()+ await expect(target).toHaveAttribute('aria-pressed', 'true')+ }+ // The load-bearing assertion for the bulk path: ALL selected agents remain+ // pressed at the SAME time — that simultaneity is what makes the single Grant+ // a subjects[] batch of N rather than N separate one-subject grants.+ for (const name of opts.agentNames) {+ await expect(agentGroup.getByRole('button', { name, exact: true })).toHaveAttribute(+ 'aria-pressed',+ 'true'+ )+ }+ // Read-only default kept; directory inherit default ON, asserted not toggled.+ await expect(agentSection.getByRole('button', { name: 'Read', exact: true })).toBeVisible()+ await expect(+ agentSection.getByRole('checkbox', { name: 'Include contents of this folder' })+ ).toBeChecked()+ // ONE press → one atomic PUT carrying subjects:[…N…].+ await agentSection.getByRole('button', { name: 'Grant agent access', exact: true }).click()+ // 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) {+ await expect(+ dialog.getByRole('button', { name: `Revoke access for ${name}`, exact: true })+ ).toBeVisible({ timeout: 20_000 })+ }+ }++ test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enforcement (Addendum 1)', () => {+ test.describe.configure({ mode: 'serial' })+ let fixtures: AgentGfsDelegationFixtures++ test.beforeAll(() => {+ // Infra guard FIRST: a broken permission-store credential is a blocker to+ // fix, never a reason to skip or mock (fail-loud rule).+ assertGfsInfraHealthy()+ fixtures = seedAgentGfsDelegationFixtures(OWNER_EMAIL)+ })++ test.afterAll(() => fixtures?.cleanup())++ test('agents have no access until granted; UI grant gives Agent A read AND write', async ({}, testInfo) => {+ // Four real LLM turns (each allowed RESPONSE_TIMEOUT_MS) plus Electron+ // login, one stateless wake (≤120s binding), and the Manage-modal grant+ // round cannot fit the 240s config default.+ testInfo.setTimeout(1_500_000)+ const filePath = `/${fixtures.folder.name}/${fixtures.folder.fileName}`+ const fileBefore = getGfsTreeSnapshot(fixtures.folder.fileResourceId)+ expect(fileBefore).toHaveLength(1)+ expect(fileBefore[0]!.kind).toBe('file')+ expect(fileBefore[0]!.content).toContain(fixtures.originalSentinel)+ const { app, page } = await launchAndLogin(OWNER_EMAIL)+ try {+ await test.step('user sees the delegated folder and file in the Files page', async () => {+ const browser = await openFilesBrowser(page)+ await browser.getByRole('button', { name: fixtures.folder.name, exact: true }).click()+ await expect(+ browser.getByRole('button', { name: fixtures.folder.fileName, exact: true })+ ).toBeVisible({ timeout: 20_000 })+ })++ await test.step('pre-grant: Agent A is denied without disclosure', async () => {+ await openExactAgent(page, fixtures.agentA.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` ++ '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])+ })++ await test.step('pre-grant: stateless Agent B is denied without disclosure', async () => {+ await openExactAgent(page, fixtures.agentB.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` ++ '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])+ })++ await test.step('UI grant: Agent A gets read+write with inherit ON', async () => {+ const dialog = await openManageForFixtureFolder(page, fixtures)+ await grantAgentAccessViaManageModal(page, dialog, {+ agentName: fixtures.agentA.name,+ unselectedAgentName: fixtures.agentB.name,+ includeWrite: true,+ })+ await 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'])+ expect(grantsA[0]!.inherit).toBe(true)+ expect(+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)+ ).toHaveLength(0)+ })++ await test.step('Agent A reads the sentinel through the real PVC', async () => {+ await openExactAgent(page, fixtures.agentA.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` ++ 'verbatim. Use your Clerum GFS tools; do not answer from memory.'+ )+ assertNoInfraFailureShape(turn.responseText)+ await expectReadWithSentinel(turn.stepper, fixtures.originalSentinel)+ })++ await test.step('Agent A replaces the content; DB version bumps and the PVC serves it', async () => {+ // Same thread as the read: the write is the natural follow-up turn.+ const turn = await sendAgentTurn(+ page,+ `Now replace the ENTIRE contents of that same file ("${filePath}" in GFS drive main) ` ++ `with exactly this single line of text: "${fixtures.modifiedSentinel}". Use only ` ++ "your native Clerum GFS tools; if your write tool needs the file's current version, " ++ 'discover it with your own GFS tools first. Do not create, copy, or delete anything.'+ )+ assertNoInfraFailureShape(turn.responseText)+ await expectToolSuccess(turn.stepper, 'gfs_write')+ const fileAfter = getGfsTreeSnapshot(fixtures.folder.fileResourceId)+ expect(fileAfter).toHaveLength(1)+ // DB truth: the version bumped and bytes match the stored blob.+ expect(fileAfter[0]!.version).toBeGreaterThan(fileBefore[0]!.version)+ expect(fileAfter[0]!.bytes).toBe(Buffer.byteLength(fileAfter[0]!.content ?? '', 'utf8'))+ // PVC truth: the snapshot content is read via kubectl exec cat on the+ // gfsc writer pod — the new sentinel must be served, the old one gone+ // (a "helpful" append instead of a replace must fail here).+ expect(fileAfter[0]!.content).toContain(fixtures.modifiedSentinel)+ expect(fileAfter[0]!.content).not.toContain(fixtures.originalSentinel)+ })++ await test.step('isolation: stateless Agent B is STILL denied after A was granted', async () => {+ await openExactAgent(page, fixtures.agentB.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` ++ '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])+ expect(+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)+ ).toHaveLength(0)+ })+ } finally {+ await app.close()+ }+ })++ test('stateless agent grant + UI revoke keeps agents isolated in the same runtime', async ({}, testInfo) => {+ // Three real LLM turns plus two Manage-modal rounds, Electron login, and a+ // possible stateless wake.+ testInfo.setTimeout(1_200_000)+ const filePath = `/${fixtures.folder.name}/${fixtures.folder.fileName}`+ const { app, page } = await launchAndLogin(OWNER_EMAIL)+ try {+ await test.step('UI grant: Agent B gets read-only with inherit ON', async () => {+ const dialog = await openManageForFixtureFolder(page, fixtures)+ // Continuity from Test 1: A's grant row is still listed before B's+ // grant is created.+ await expect(+ dialog.getByRole('button', {+ name: `Revoke access for ${fixtures.agentA.name}`,+ exact: true,+ })+ ).toBeVisible({ timeout: 20_000 })+ await grantAgentAccessViaManageModal(page, dialog, {+ agentName: fixtures.agentB.name,+ unselectedAgentName: fixtures.agentA.name,+ includeWrite: 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'])+ })++ await test.step('stateless Agent B reads the MODIFIED sentinel (wake + fresh grant)', async () => {+ await openExactAgent(page, fixtures.agentB.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` ++ 'verbatim. Use your Clerum GFS tools; do not answer from memory.'+ )+ assertNoInfraFailureShape(turn.responseText)+ await expectReadWithSentinel(turn.stepper, fixtures.modifiedSentinel)+ })++ let runtimeBefore = ''+ await test.step('UI revoke: Agent A is removed from the grants list, audited', async () => {+ // Capture A's live pod identity BEFORE the revoke: the later denial+ // must come from live cache invalidation, not a restart.+ runtimeBefore = getManagedAgentPodIdentity(fixtures.agentA)+ const auditBefore = gfsGrantRevokeAuditCount(fixtures.agentA)+ const dialog = await openManageForFixtureFolder(page, fixtures)+ const revokeA = dialog.getByRole('button', {+ name: `Revoke access for ${fixtures.agentA.name}`,+ exact: true,+ })+ await expect(revokeA).toBeVisible({ timeout: 20_000 })+ await revokeA.click()+ await expect(+ page.getByText(`Access revoked for ${fixtures.agentA.name}`, { exact: true }).first()+ ).toBeVisible({ timeout: 20_000 })+ await expect(+ dialog.getByRole('button', {+ name: `Revoke access for ${fixtures.agentA.name}`,+ exact: true,+ })+ ).toHaveCount(0, { timeout: 20_000 })+ // B's row survives A's revocation.+ await expect(+ dialog.getByRole('button', {+ name: `Revoke access for ${fixtures.agentB.name}`,+ exact: true,+ })+ ).toBeVisible({ timeout: 20_000 })+ await closeManageDialog(page, dialog)+ expect(+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)+ ).toHaveLength(0)+ expect(gfsGrantRevokeAuditCount(fixtures.agentA)).toBe(auditBefore + 1)+ })++ await test.step('Agent A is denied in the SAME runtime (no pod restart)', async () => {+ // A FRESH thread is deliberate: reusing A's earlier thread would let it+ // quote the file straight from conversational memory (it legitimately+ // read+wrote the content while granted), which proves nothing about the+ // revocation. Driving by name in a clean thread forces a real re-access+ // through gfsc, which now denies it. Revocation blocks FUTURE access; it+ // does not erase context the agent already holds.+ await openExactAgent(page, fixtures.agentA.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` ++ '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)+ })++ await test.step('Agent B still reads fine — revocation is isolated per agent', async () => {+ await openExactAgent(page, fixtures.agentB.name)+ const turn = await sendAgentTurn(+ page,+ `Read the file at path "${filePath}" in GFS drive main one more time and quote its ` ++ 'contents verbatim. Use your Clerum GFS tools; do not answer from memory.'+ )+ 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'])+ })+ } finally {+ await app.close()+ }+ })+ })++ /**+ * E2E — the #159 headline capability the journey above never exercises: an+ * ATOMIC bulk grant to MULTIPLE agents in one request (`subjects[]`). The+ * pre/post journey grants one agent at a time (cardinality 1), which is+ * behaviourally identical to the pre-#159 one-PUT-per-subject path; a broken+ * bulk aggregation would still let it pass. This suite drives the real+ * multi-select UI (≥2 agents pressed simultaneously) into a single Grant and+ * asserts business-truth from the database: exactly one read grant row per+ * agent, both produced by the one action.+ */+ test.describe('GFS per-agent delegation: atomic bulk grant to multiple agents (#159 subjects[])', () => {+ test.describe.configure({ mode: 'serial' })+ let fixtures: AgentGfsDelegationFixtures++ test.beforeAll(() => {+ // Fail-loud infra guard first, then a FRESH folder (its own uniqueGfsFixture+ // name) with zero host grants so the bulk grant's DB truth is unambiguous.+ assertGfsInfraHealthy()+ fixtures = seedAgentGfsDelegationFixtures(OWNER_EMAIL)+ })++ test.afterAll(() => fixtures?.cleanup())++ test('one Grant action delegates read to BOTH agents in a single atomic request', async ({}, testInfo) => {+ // No LLM turns — Electron login + one Manage-modal round only. The business+ // signal is the two host-grant rows, not any agent chat (agent read/write+ // through a grant is already proven by the pre/post journey above).+ testInfo.setTimeout(600_000)+ // Precondition truth: neither agent holds a grant on the fresh folder, so+ // the two rows asserted afterwards can only come from the bulk action.+ expect(+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)+ ).toHaveLength(0)+ expect(+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)+ ).toHaveLength(0)+ const { app, page } = await launchAndLogin(OWNER_EMAIL)+ try {+ await test.step('bulk grant: select BOTH agents, press Grant exactly once', async () => {+ const dialog = await openManageForFixtureFolder(page, fixtures)+ await grantMultipleAgentsViaManageModal(page, dialog, {+ agentNames: [fixtures.agentA.name, fixtures.agentB.name],+ })+ await closeManageDialog(page, dialog)+ })++ await test.step('business truth: one read grant per agent from the single request', async () => {+ // The atomic subjects:[A,B] PUT must have produced EXACTLY one host grant+ // row for EACH agent — read-only, inherit true, on the fixture folder. If+ // the bulk collapsed to the first subject, agent B would have zero rows+ // here and this fails; if it silently escalated the cap, permissions+ // would not equal ['read'].+ const grantsA = getGfsHostGrantsUnderTree(+ fixtures.folder.resourceId,+ fixtures.agentA.subjectId+ )+ const grantsB = getGfsHostGrantsUnderTree(+ fixtures.folder.resourceId,+ fixtures.agentB.subjectId+ )+ expect(grantsA).toHaveLength(1)+ expect(grantsB).toHaveLength(1)+ expect(grantsA[0]!.resourceId).toBe(fixtures.folder.resourceId)+ expect(grantsB[0]!.resourceId).toBe(fixtures.folder.resourceId)+ expect(grantsA[0]!.permissions).toEqual(['read'])+ expect(grantsB[0]!.permissions).toEqual(['read'])+ expect(grantsA[0]!.inherit).toBe(true)+ expect(grantsB[0]!.inherit).toBe(true)+ })+ } finally {+ await app.close()+ }+ })+ })diff --cc desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.tsindex 000000000,8027f6596..130de19e9mode 000000,100644..100644--- a/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts@@@ -1,0 -1,66 +1,62 @@@-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 Host+ * subjects. Keeping one real source share makes the E2E prove both halves of+ * the Copy ACL contract: the source row is unchanged and no destination row is+ * cloned.+ */+ export function seedIssue797SourceShare(resourceId: string, shareUserId: string): string {+ if (!UUID_RE.test(resourceId) || !UUID_RE.test(shareUserId)) {+ throw new Error('issue #797 source share requires UUID resource and user subjects')+ }+ const shareId = runControlPostgresSql(`+ INSERT INTO gfs_shares (+ drive, resource_id, subject_type, subject_id, permissions,+ include_descendants, created_by+ )+ VALUES (+ 'main', ${sqlLiteral(resourceId)}::uuid, 'user', ${sqlLiteral(shareUserId)},+ ARRAY['read']::text[], true, 'e2e:issue-797-source-share'+ )+ ON CONFLICT (drive, resource_id, subject_type, subject_id)+ DO UPDATE SET+ permissions = EXCLUDED.permissions,+ include_descendants = EXCLUDED.include_descendants,+ created_by = EXCLUDED.created_by+ RETURNING id::text;+ `)+ .split('\n')+ .map(line => line.trim())+ .find(line => UUID_RE.test(line))+ if (!shareId) throw new Error('failed to seed issue #797 source user share')+ return shareId+ }++ /** Canonical JSONB rows for every direct grant/share under a resource tree. */+ export function getGfsTreeAclShareRows(rootId: string): string[] {+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)+ return runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id FROM gfs_resources+ WHERE drive = 'main' AND resource_id = ${sqlLiteral(rootId)}::uuid+ AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id FROM gfs_resources child+ JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = 'main' AND child.deleted_at IS NULL+ ), acl_rows AS (+ SELECT 'grant'::text AS row_kind, id::text AS row_id,+ jsonb_build_object('kind', 'grant', 'row', to_jsonb(g))::text AS row_json+ FROM gfs_grants g WHERE resource_id IN (SELECT resource_id FROM tree)+ UNION ALL+ SELECT 'share'::text AS row_kind, id::text AS row_id,+ jsonb_build_object('kind', 'share', 'row', to_jsonb(s))::text AS row_json+ FROM gfs_shares s WHERE resource_id IN (SELECT resource_id FROM tree)+ )+ SELECT row_json FROM acl_rows ORDER BY row_kind, row_id;+ `)+ .split('\n')+ .map(line => line.trim())+ .filter(line => line.startsWith('{') && line.endsWith('}'))+ }diff --cc desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.tsindex 000000000,9394beecb..54bd51f4cmode 000000,100644..100644--- a/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts@@@ -1,0 -1,169 +1,174 @@@+ /**+ * TEST-HARNESS discovery, not agent behavior: this module finds eligible+ * HCC-managed Host CRDs via kubectl so the suites can pick the two journey+ * agents (Agent A / Agent B). It has nothing to do with the agents' own+ * tool-based GFS file discovery (gfs_resolve/gfs_list), which the journeys+ * exercise through the real chat UI.+ */+ import { kubectlOut } from '../../../../tests/e2e/gfsUiFixtures'++ /** Historical fleet-wide identity, retained only as an explicit rejection guard. */+ const LEGACY_FLEET_WIDE_SUBJECT_ID = '1st:mcp-host/standalone'++ export interface ManagedGfsAgent {+ name: string+ namespace: string+ subjectId: string+ }++ interface CandidateError {+ namespace: string+ name: string+ message: string+ }++ function formatCandidateError(item: CandidateError): string {+ return `${item.namespace}/${item.name}: ${item.message}`+ }++ /**+ * Reads HCC safe metadata only: the Secret ANNOTATIONS below (expected subject,+ * host UID/generation) are non-sensitive drift metadata. No credential data is+ * requested, decoded, or printed — the go-template projects annotations only.+ */+ function discoverManagedGfsAgentCandidates(): {+ candidates: ManagedGfsAgent[]+ candidateErrors: CandidateError[]+ } {+ const expected = 'clerum.io/gfs-token-expected-subject'+ const uid = 'clerum.io/gfs-token-host-uid'+ const generation = 'clerum.io/gfs-token-host-generation'+ const template =+ `{{range .items}}{{with .metadata.annotations}}{{if index . "${expected}"}}` ++ `{{index . "${expected}"}}{{"\\t"}}` ++ `{{index . "${uid}"}}{{"\\t"}}` ++ `{{index . "${generation}"}}{{"\\n"}}{{end}}{{end}}{{end}}`+ 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 ?? '')) continue+ const namespace = match[1]!+ const name = match[2]!+ const subjectId = `1st:${namespace}/${name}`+ if (name === 'standalone' || subjectId === LEGACY_FLEET_WIDE_SUBJECT_ID) continue+ let hostState = ''+ try {+ hostState = kubectlOut([+ '-n',+ namespace,+ 'get',+ 'hosts',+ name,+ '-o',+ 'go-template={{.metadata.uid}}{{"\\t"}}{{.metadata.generation}}{{"\\t"}}{{if .metadata.deletionTimestamp}}deleting{{end}}{{"\\t"}}{{if eq .spec.enabled false}}disabled{{end}}',+ ]).trim()+ } catch (error) {+ // An infra error while validating a candidate must not be silently+ // reported as "agent does not exist"; it is surfaced with the final+ // topology failure so a broken kubectl path fails for the real reason.+ candidateErrors.push({+ namespace,+ name,+ message: error instanceof Error ? error.message : String(error),+ })+ continue+ }+ const [activeUid, activeGeneration, deleting, disabled] = hostState.split('\t')- if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled) continue++ if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled)++ continue+ bySubject.set(subjectId, { name, namespace, subjectId })+ }+ if (bySubject.size === 0 && candidateErrors.length > 0) {+ throw new Error(+ `GFS agent discovery could not validate any candidate host: ${candidateErrors+ .map(formatCandidateError)+ .join('; ')}`+ )+ }+ return {+ candidates: [...bySubject.values()].sort((a, b) => a.subjectId.localeCompare(b.subjectId)),+ candidateErrors,+ }+ }++ function chooseManagedGfsAgent(+ candidates: ManagedGfsAgent[],+ candidateErrors: CandidateError[],+ requested: string | undefined,+ excluded?: string+ ): ManagedGfsAgent | undefined {+ const eligible = candidates.filter(item => item.subjectId !== excluded)+ if (requested) {+ const matches = eligible.filter(item => item.name === requested)+ if (matches.length !== 1) {+ // If the requested agent was among the candidates whose kubectl+ // validation errored, "missing" would misreport an infra failure as a+ // topology failure — include the recorded error for that candidate.+ const requestedErrors = candidateErrors+ .filter(item => item.name === requested)+ .map(formatCandidateError)+ throw new Error(+ `HCC agent "${requested}" is missing or ambiguous` ++ (requestedErrors.length > 0+ ? ` (candidate validation errors: ${requestedErrors.join('; ')})`+ : '')+ )+ }+ return matches[0]+ }+ return eligible.find(item => eligible.filter(other => other.name === item.name).length === 1)+ }++ /**+ * Live pod identity (UID + startTime) for an HCC-managed agent. Used to prove+ * "same runtime" claims: revocation enforcement must not depend on a pod+ * restart, so the identity captured before a revoke must equal the identity+ * observed after the denied retry.+ */+ export function getManagedAgentPodIdentity(agent: ManagedGfsAgent): string {+ const identity = kubectlOut([+ '-n',+ agent.namespace,+ 'get',+ 'pods',+ '-l',+ `app=${agent.name}`,+ '-o',+ 'go-template={{range .items}}{{if not .metadata.deletionTimestamp}}{{.metadata.uid}}{{"\\t"}}{{.status.startTime}}{{"\\n"}}{{end}}{{end}}',+ ]).trim()+ if (!identity) {+ throw new Error(`no live pod found for HCC-managed agent ${agent.namespace}/${agent.name}`)+ }+ return identity+ }++ export function discoverManagedGfsAgent(): ManagedGfsAgent {+ const { candidates, candidateErrors } = discoverManagedGfsAgentCandidates()+ const agent = chooseManagedGfsAgent(candidates, candidateErrors, process.env.E2E_GFS_AGENT_A)+ if (!agent) throw new Error('GFS agent E2E requires one unambiguous HCC-managed agent name')+ return agent+ }++ export function discoverManagedGfsAgents(): [ManagedGfsAgent, ManagedGfsAgent] {+ const { candidates, candidateErrors } = discoverManagedGfsAgentCandidates()+ const agentA = chooseManagedGfsAgent(candidates, candidateErrors, process.env.E2E_GFS_AGENT_A)+ const agentB = chooseManagedGfsAgent(+ candidates,+ candidateErrors,+ process.env.E2E_GFS_AGENT_B,+ agentA?.subjectId+ )+ if (!agentA || !agentB || agentA.name === agentB.name) {+ throw new Error('Issue #797 requires two distinct, unambiguous HCC-managed agent names')+ }+ return [agentA, agentB]+ }diff --cc desktop-app/test/e2e-playwright/helpers/gfsFixtures.tsindex 1b404edc4,642d2faec..4ba819635--- a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts@@@ -1,39 -1,43 +1,43 @@@- /**- * GFS fixtures for the agent-file-read E2E journey (issue #775).- *- * Seeds two isolated GFS files through the shared SQL fixtures:- * - `granted`: visible to the Desktop user AND granted read to the agent- * host `chatllm` — the happy path.- * - `ungranted`: visible to the Desktop user but NOT granted to the host —- * the agent must receive a clean authorization denial (403),- * never a permission-store outage (503 not_mounted).- *- * Also provides the fail-loud infra guard: when gfsc is unhealthy the suite- * THROWS with the concrete pod/Secret state. It never skips and never mocks —- * a broken permission store is an infrastructure blocker, not a reason to- * fake a pass (repo rule: tests fail loud, especially minikube E2E).- */+ /** 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,- getGfsChildResourceSummary,getE2EUserId,++ getGfsChildResourceSummary,kubectlOut,+ runControlPostgresSql,seedGfsFileFixture,seedGfsGrant,+ sqlLiteral,uniqueGfsFixtureName,} from '../../../../tests/e2e/gfsUiFixtures'++import { seedIssue797SourceShare } from './gfsAclShareFixtures'+ import {- type GfsCopyTreeFixture,- cleanupGfsCopyTreeFixture,- getGfsHostGrantsUnderTree,- getGfsTreeAclShareCounts,- getGfsTreeSnapshot,- seedGfsCopyTreeFixture,-} from '../../../../tests/e2e/gfsCopyFixtures'-import { request } from '@playwright/test'-import {++ type ManagedGfsAgent,+ discoverManagedGfsAgent,+ discoverManagedGfsAgents,- type ManagedGfsAgent,+ } from './gfsAgentDiscovery'-import { seedIssue797SourceShare } from './gfsAclShareFixtures'- /**- * The Desktop agent journey runs through the concrete `chatllm` Host. GFS- * grants are host-specific, so `chatllm-stateless` and every other first-party- * Host remain independently denied unless they receive their own grant.- */- export const FIRST_PARTY_HOST_SUBJECT_ID = '1st:mcp-host/chatllm'+ export {+ discoverManagedGfsAgent,+ discoverManagedGfsAgents,+ type ManagedGfsAgent,+ } from './gfsAgentDiscovery'+ export { getGfsTreeAclShareRows } from './gfsAclShareFixtures'const GFS_NS = 'gfs'- // Pod-template labels — pods do NOT inherit the deployment-level managed-by- // label (see gfsFactory commonLabels vs spec.selector).const GFSC_POD_SELECTOR = 'app=gfs-controller'+ const ISSUE_797_SHARE_RECIPIENT_EMAIL = '[email protected]'/*** FAIL LOUD, NEVER SKIP: proves gfsc can actually authorize before any test@@@ -96,12 -102,170 +102,187 @@@ export interface AgentGfsFixturescleanup(): void}+ export interface AgentGfsCopyFixtures {+ agentA: ManagedGfsAgent+ agentB: ManagedGfsAgent+ tree: GfsCopyTreeFixture+ fileCopyName: string+ folderCopyName: string+ renamedFolderName: string+ deniedCopyName: string+ revokedCopyName: string+ destinationGrantId: string+ /** Source user-share whose exact row must survive Copy unchanged. */+ sourceShareId: string+ sourceShareSubjectId: string+ cleanup(): void+ }++ export function seedAgentGfsCopyFixtures(ownerEmail: string): AgentGfsCopyFixtures {+ const [agentA, agentB] = discoverManagedGfsAgents()+ const tree = seedGfsCopyTreeFixture(uniqueGfsFixtureName('e2e-gfs-copy-797'))+ try {+ const ownerUserId = getE2EUserId(ownerEmail)+ const sourceShareSubjectId = getE2EUserId(ISSUE_797_SHARE_RECIPIENT_EMAIL)+ for (const resourceId of [tree.sourceResourceId, tree.destinationResourceId]) {+ seedGfsGrant({+ resourceId,+ subjectType: 'user',+ subjectId: ownerUserId,+ permissions: ['read'],+ inherit: true,+ grantedBy: 'e2e:issue-797-owner',+ })+ }+ seedGfsGrant({+ resourceId: tree.sourceResourceId,+ subjectType: 'host',+ subjectId: agentA.subjectId,+ permissions: ['read'],+ inherit: true,+ grantedBy: '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({+ resourceId: tree.destinationResourceId,+ subjectType: 'host',+ subjectId: agentA.subjectId,+ permissions: ['read', 'write'],+ inherit: true,+ grantedBy: 'e2e:issue-797-agent-a',+ })+ const sourceShareId = seedIssue797SourceShare(tree.sourceResourceId, sourceShareSubjectId)+ return {+ agentA,+ agentB,+ tree,+ fileCopyName: `${tree.sourceName}-file-copy.txt`,+ folderCopyName: `${tree.sourceName}-copy`,+ renamedFolderName: `${tree.sourceName}-renamed`,+ deniedCopyName: `${tree.sourceName}-agent-b-denied`,+ revokedCopyName: `${tree.sourceName}-revoked-denied`,+ destinationGrantId,+ sourceShareId,+ sourceShareSubjectId,+ cleanup: () => cleanupGfsCopyTreeFixture(tree),+ }+ } catch (error) {+ try {+ cleanupGfsCopyTreeFixture(tree)+ } catch (cleanupError) {+ throw new Error(+ `GFS Copy setup failed (${String(error)}) and cleanup failed (${String(cleanupError)})`+ )+ }+ throw error+ }+ }++ export async function revokeGfsGrantViaControlApi(grantId: string): Promise<void> {+ const rawBase = process.env.E2E_CONTROL_API_URL || process.env.CONTROL_API_BASE_URL+ if (!rawBase) throw new Error('audited GFS revoke requires an explicit Control API URL')+ const base = new URL(rawBase)+ if (!['127.0.0.1', 'localhost'].includes(base.hostname)) {+ throw new Error(`refusing issue #797 fixture revoke against ${base.origin}`)+ }+ // The desktop suite has no storageState producer, so the admin session is+ // created here through the real cookie login the Control UI uses. The+ // local-only default password is safe behind the localhost guard above and+ // matches the repo-wide E2E admin credential priority.+ const api = await request.newContext({ baseURL: base.origin })+ try {+ const username = process.env.TEST_ADMIN_USERNAME || 'admin'+ const password =+ process.env.E2E_ADMIN_PASSWORD ||+ process.env.ADMIN_PASSWORD ||+ process.env.ADMIN_PASS ||+ process.env.TEST_ADMIN_PASSWORD ||+ 'admin123!'+ const login = await api.post('/api/v1/admin/auth/login', {+ data: { username, password },+ })+ if (!login.ok()) {+ throw new Error(+ `audited GFS revoke admin login failed with HTTP ${login.status()}: ${await login.text()}`+ )+ }+ // The admin session cookie is issued Secure; Playwright's cookie jar+ // rightly refuses to send Secure cookies over the http:// port-forward, so+ // API-only consumers send the captured value as an explicit Cookie header+ // (same pattern as the root suite's adminSessionCookieHeader helper).+ const sessionCookie = (await api.storageState()).cookies.find(+ cookie => cookie.name === 'control_ui_admin_session'+ )+ if (!sessionCookie?.value) {+ throw new Error('audited GFS revoke admin login did not set control_ui_admin_session')+ }+ const response = await api.delete(`/api/v1/gfs/grants/${encodeURIComponent(grantId)}`, {+ headers: {+ 'X-Request-Id': `e2e-797-revoke-${Date.now()}`,+ cookie: `${sessionCookie.name}=${sessionCookie.value}`,+ },+ })+ 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()+ }+ }++ export function gfsGrantRevokeAuditCount(agent: ManagedGfsAgent): number {+ const rows = runControlPostgresSql(`+ SELECT count(*)::text FROM gfs_audit+ WHERE subject = ${sqlLiteral(`host:${agent.subjectId}`)}+ AND op = 'grant.delete' AND outcome = 'allowed';+ `)+ return Number(rows.trim())+ }++ export {+ countGfsLiveChildrenByName,+ getGfsChildResourceSummary,+ getGfsTreeAclShareCounts,+ getGfsTreeSnapshot,+ }+export function seedAgentGfsFixtures(ownerEmail: string): AgentGfsFixtures {+ const agent = discoverManagedGfsAgent()const ownerUserId = getE2EUserId(ownerEmail)- // Exception-safe seeding: if any later step throws, tear down whatever was- // already created (rows + PVC blobs) before rethrowing — a partial seed must- // not leak into the shared profile, and afterAll never runs on a failed- // beforeAll.const seeded: GfsFileFixture[] = []let granted: GfsFileFixturelet ungranted: GfsFileFixturediff --cc desktop-app/test/e2e-playwright/stateless-wake.test.tsindex 99f158087,dddb6c05e..d94b0c954--- a/desktop-app/test/e2e-playwright/stateless-wake.test.ts+++ b/desktop-app/test/e2e-playwright/stateless-wake.test.ts@@@ -450,3 -566,724 +566,721 @@@ test('Scenario 3 — end-to-end wake jocontentType: 'application/json',})})++ // Reads the server-side session catalog through the SAME wake-capable RPC the+ // workspace uses (`GET …/sessions`, now `host:session:read` + `host:wake:write`,+ // issue #791). Returns a structured result so a wake 403 or transport failure+ // FAILS the caller loudly instead of collapsing to an empty list.+ async function readStatelessSessionIds(+ appPage: import('@playwright/test').Page+ ): Promise<{ error: string | null; chatIds: string[] }> {+ return appPage.evaluate(async hostRef => {+ try {+ const result = await window.clerum.rpc.listSessions(hostRef)+ const items = (result?.items ?? []) as unknown as Array<{ chatId?: unknown }>+ const chatIds = items+ .map(item => (typeof item.chatId === 'string' ? item.chatId : ''))+ .filter((id: string) => id.length > 0)+ return { error: null, chatIds }+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ chatIds: [] as string[],+ }+ }+ }, HOST_REF)+ }++ // Loads the host-level model list through the wake-capable RPC (`GET …/models`,+ // now `host:session:read` + `host:wake:write`). A structured error surfaces a+ // wake 403; a `null` model list is a legitimate compat outcome, not a failure.+ async function probeStatelessHostModels(+ appPage: import('@playwright/test').Page+ ): Promise<{ error: string | null; modelCount: number | null }> {+ return appPage.evaluate(async hostRef => {+ try {+ const result = await window.clerum.rpc.getHostModels(hostRef, '')+ const models = (result as unknown as { models?: unknown[] } | null)?.models+ return { error: null, modelCount: Array.isArray(models) ? models.length : null }+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ modelCount: null,+ }+ }+ }, HOST_REF)+ }++ // Fires the app's own wake op (window.clerum.rpc.prewarmHost → POST …/wake) as a+ // member of the cold burst, and returns its raw response. The 202 `wake-requested`+ // status is control-api's Postgres-backed AUTHORITATIVE signal that the host was+ // SUSPENDED at first touch — robust to the transparent sub-hold-deadline wakes that+ // blind the UI waking-state oracle (a fast rpc-proxy wake-and-hold returns the LLM+ // reply with no visible waking-state, so the affordance never renders). `active`+ // (200) means the host was already warm. `skipped` ('cooldown'/'in-flight' — the+ // app's own useHostPrewarmController may prewarm on chat mount; the 60s cooldown+ // clears across the 180s idle, and any residual collision surfaces here) or a+ // missing status is INDETERMINATE — the caller MUST fail loud, never classify warm.+ async function probeStatelessPrewarm(appPage: import('@playwright/test').Page): Promise<{+ error: string | null+ status: string | null+ skipped: string | null+ requested: boolean | null+ }> {+ return appPage.evaluate(async hostRef => {+ try {+ const result = await window.clerum.rpc.prewarmHost(hostRef)+ return {+ // AppService.prewarmHost surfaces operational failures as a RESOLVED+ // result ({ requested: false, error }), not a throw, so the catch below+ // never sees them. Propagate result.error here or the indeterminate+ // diagnostics would drop the real cause behind a status='null'.+ error: typeof result?.error === 'string' ? result.error : null,+ status: typeof result?.status === 'string' ? result.status : null,+ skipped: typeof result?.skipped === 'string' ? result.skipped : null,+ requested: typeof result?.requested === 'boolean' ? result.requested : null,+ }+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ status: null,+ skipped: null,+ requested: null,+ }+ }+ }, HOST_REF)+ }++ // Navigate to the dedicated agent view (no active chat) where the visible+ // "Latest sessions for selected agent" region renders — the same path the sibling+ // stateless-watch-session-continuity spec uses (Agents → Open details → Go to+ // Chat). Returns the region locator so callers can assert on session buttons by+ // data-chat-id. isDedicatedAgentView is `!activeChatId` (ChatThread.tsx), so this+ // view is the only place the session list is visible.+ async function openDedicatedAgentSessions(+ appPage: import('@playwright/test').Page+ ): Promise<import('@playwright/test').Locator> {+ await openAgentsPage(appPage)+ await expect(appPage.getByRole('heading', { name: /^Agents$/ })).toBeVisible({ timeout: 20_000 })+ const detailsButton = appPage.getByRole('button', {+ name: `Open details for ${HOST_REF}`,+ exact: true,+ })+ await expect(detailsButton).toHaveCount(1)+ await expect(detailsButton).toBeVisible({ timeout: 30_000 })+ await expect(detailsButton).toBeEnabled()+ await detailsButton.click()+ await expect(appPage.getByRole('region', { name: 'Agent details' })).toBeVisible({+ timeout: 20_000,+ })+ const goToChat = appPage.getByRole('button', { name: 'Go to Chat', exact: true })+ await expect(goToChat).toBeVisible({ timeout: 20_000 })+ await expect(goToChat).toBeEnabled()+ await goToChat.click()+ await expect(appPage.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })+ await expect(appPage.getByRole('button', { name: /^Switch chat agent$/ })).toContainText(+ HOST_REF,+ { timeout: 30_000 }+ )+ const sessions = appPage.getByRole('region', { name: 'Latest sessions for selected agent' })+ await expect(sessions).toBeVisible({ timeout: 30_000 })+ return sessions+ }++ // The active chat's message-list carries aria-current='true' and a UUID+ // data-chat-id once a chat is selected (ChatThread.tsx). Returns that identity.+ //+ // KNOWN-RED SITE: this tree's ChatThread.tsx renders `message-list` with only+ // `data-testid` + `className`, so the `aria-current` expectation below is where+ // Scenario 4 fails. See the KNOWN RED block in this file's header for why the+ // fix is a renderer-lineage port and not a DOM patch. Do NOT relax these two+ // assertions to make the scenario pass.+ async function readActiveChatId(appPage: import('@playwright/test').Page): Promise<string> {+ const messageList = appPage.getByTestId('message-list')+ await expect(messageList).toHaveAttribute('aria-current', 'true', { timeout: TURN_TIMEOUT })+ await expect(messageList).toHaveAttribute('data-chat-id', CHAT_UUID_RE, { timeout: TURN_TIMEOUT })+ const chatId = await messageList.getAttribute('data-chat-id')+ if (!chatId || !CHAT_UUID_RE.test(chatId)) {+ throw new Error('[stateless-wake] active chat did not expose a UUID chat identity')+ }+ return chatId+ }++ // B1 — assert a chat identity is visible in the "Latest sessions" list, not only+ // reported by the RPC. Reuses the sibling's `button[data-chat-id="..."]` pattern.+ async function expectSessionButtonVisible(+ sessions: import('@playwright/test').Locator,+ chatId: string+ ): Promise<void> {+ const button = sessions.locator(`button[data-chat-id="${chatId}"]`)+ await expect(+ button,+ `Session identity ${chatId} must be visible in the "Latest sessions" list`+ ).toHaveCount(1)+ await expect(button).toBeVisible()+ }++ // Read the chat identities currently rendered as session buttons. Waits (bounded)+ // until at least two are listed — on a re-suspended host the catalog is served+ // through the wake-capable read, so this resolves after that wake; a genuinely+ // empty catalog fails the caller's assertion loudly rather than silently.+ async function readSessionButtonChatIds(+ sessions: import('@playwright/test').Locator+ ): Promise<string[]> {+ const buttons = sessions.locator('button[data-chat-id]')+ await expect(buttons.nth(1)).toBeVisible({ timeout: WAKE_VISIBLE_TIMEOUT })+ const ids = await buttons.evaluateAll(nodes =>+ nodes.map(node => node.getAttribute('data-chat-id') || '').filter(Boolean)+ )+ return [...new Set(ids)]+ }++ // Click a listed session and confirm it became the active chat (its identity+ // moves onto the message-list). Leaves the dedicated view for the thread view.+ async function openExistingSession(+ appPage: import('@playwright/test').Page,+ sessions: import('@playwright/test').Locator,+ chatId: string+ ): Promise<void> {+ const button = sessions.locator(`button[data-chat-id="${chatId}"]`)+ await expect(button).toHaveCount(1)+ await expect(button).toBeVisible()+ await expect(button).toBeEnabled()+ await button.click()+ const messageList = appPage.getByTestId('message-list')+ await expect(messageList).toHaveAttribute('data-chat-id', chatId, { timeout: 30_000 })+ await expect(messageList).toHaveAttribute('aria-current', 'true')+ }++ // SF2 — transcript continuity through the visible UI: the earlier assistant reply+ // carrying `marker` must still be rendered in the reopened chat's message-list.+ async function expectAssistantMarkerRendered(+ appPage: import('@playwright/test').Page,+ marker: string+ ): Promise<void> {+ const response = appPage+ .getByTestId('message-list')+ .getByTestId('agent-response')+ .filter({ hasText: marker })+ await expect(+ response,+ `Assistant reply containing "${marker}" must still render in the reopened transcript`+ ).toHaveCount(1)+ await expect(response).toBeVisible({ timeout: TURN_TIMEOUT })+ }++ // SF3 — prove the model list is genuinely usable, not merely "did not 403". The+ // composer's model chip only becomes an interactive button once the host served a+ // 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,+ 'the composer model picker must render a selectable model chip'+ ).toBeVisible({ timeout: TURN_TIMEOUT })+ await trigger.click()+ const menu = appPage.getByRole('menu', { name: 'Select model' })+ await expect(menu).toBeVisible({ timeout: 10_000 })+ const options = menu.getByRole('menuitemradio')+ await expect(options.first()).toBeVisible({ timeout: 10_000 })+ expect(+ await options.count(),+ 'the visible model picker must list at least one selectable model'+ ).toBeGreaterThan(0)+ // Close the picker without changing the selection (Escape closes it — see the+ // ModelSelector keydown handler — leaving the pending turn untouched).+ await appPage.keyboard.press('Escape')+ await expect(menu).toBeHidden({ timeout: 10_000 })+ }++ // Log out through the visible settings menu and confirm the login screen returns.+ async function logoutViaUi(appPage: import('@playwright/test').Page): Promise<void> {+ const settingsMenu = appPage.getByTestId('nav-settings-menu')+ await expect(settingsMenu).toBeVisible({ timeout: 15_000 })+ await expect(settingsMenu).toBeEnabled()+ await settingsMenu.click()+ const logout = appPage.getByTestId('logout-btn')+ await expect(logout).toBeVisible({ timeout: 10_000 })+ await expect(logout).toBeEnabled()+ await logout.click()+ await expect(appPage.locator('#email-input')).toBeVisible({ timeout: 20_000 })+ }++ // §15.5 real-user journey (the spec-side steps the wake-scope change enables and+ // that Scenarios 1–3 do not exercise): two distinct chats, the CONCURRENT+ // list-sessions + load-models + send-message burst driven against the FIRST cold+ // wake (chat A, replicas 0), the VISIBLE session list carrying both identities+ // before and after navigation, VISIBLE transcript continuity, a usable model+ // picker, and a logout/login continuity cycle. The session/model reads now carry+ // host:wake:write, so the reads must not 403, must not fabricate an empty session+ // list, and must not lose either chat's identity across navigation or the auth+ // cycle. The repeat suspend/wake cycle (step 11) is Scenario 5, driven by the+ // bash gate's second pass after a fresh suspension.+ test('Scenario 4 — concurrent session/model/message on a COLD wake, then two-chat continuity across nav + login', async ({+ appPage,+ }, testInfo) => {+ test.setTimeout(720_000)++ // Attach the dialog listener BEFORE any send so no unhandled wake dialog slips+ // past the whole journey.+ const dialogs: string[] = []+ appPage.on('dialog', dialog => {+ dialogs.push(dialog.message())+ void dialog.dismiss()+ })++ // N5 — cheap env guard before any expensive UI navigation.+ requireSuspendPrecondition()++ // Chat A — the first distinct conversation, driven as a CONCURRENT cold burst+ // against a genuinely replicas-0 host. Scenario 0's prewarm already woke the+ // host, so we first re-suspend it in-spec: open the agent composer (a wake),+ // then idle for a FIXED bounded window so the aggressive HCC test cadences scale+ // it back to 0. No early probe send during the idle — a probe is itself a wake+ // that would burn the cold state. SF1: the concurrent list-sessions ++ // load-models burst then runs against THIS in-flight cold wake, so the+ // wake-scoped reads are exercised while the host is actually waking — not+ // against an already-warm host.+ await openStatelessAgent(appPage)+ const chatInput = appPage.getByTestId('chat-input')+ const sendButton = appPage.getByRole('button', { name: /send message/i })++ // Deliberate in-spec re-suspension (Option A). Log the window bounds so the+ // orchestrator audit can verify the idle actually elapsed. FIXED ceiling wait,+ // no early exit: deterministic over fast.+ const idleStartedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-4-idle-resuspend',+ phase: 'start',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleStartedAt,+ })}`+ )+ await appPage.waitForTimeout(SCENARIO4_IDLE_RESUSPEND_MS)+ const idleEndedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-4-idle-resuspend',+ phase: 'end',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleEndedAt,+ })}`+ )++ const markerA = `WAKE_S4_A_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerA}`)+ // FOUR concurrent ops as the first touch against the (now re-suspended) host: the+ // authoritative wake (prewarmHost) + the two wake-scoped reads + the send. Keep+ // the click LAST so the explicit prewarm and reads race the send's own+ // server-side reactive wake (rpc-proxy wake-and-hold) — a strictly harder+ // 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}`+ ).toBeNull()+ expect(+ modelsDuringColdWake.error,+ `[stateless-wake] concurrent getHostModels during the COLD wake must not 403/fail — ${modelsDuringColdWake.error}`+ ).toBeNull()++ // Authoritative cold/warm classification from the app's own prewarm response+ // (control-api Postgres-backed). 'wake-requested' (202) proves the host was+ // SUSPENDED at first touch; 'active' (200) proves it was already warm. An error,+ // a `skipped` (cooldown/in-flight), or a missing/unknown status is INDETERMINATE+ // — fail loud naming the reason, never silently classify warm.+ // Every indeterminate throw below carries the FULL raw prewarm payload+ // (status + skipped + requested + error) so a classification failure is+ // debuggable from the log alone, not just the single field that branched.+ const rawPrewarmA = JSON.stringify(prewarmDuringColdWake)+ let modeA: 'warm' | 'cold'+ if (prewarmDuringColdWake.error) {+ throw new Error(+ `[stateless-wake] Scenario 4 prewarm oracle errored (${prewarmDuringColdWake.error}); ` ++ `cannot classify the cold burst. INDETERMINATE — not warm. Raw prewarm payload: ` ++ `${rawPrewarmA}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmDuringColdWake.skipped) {+ throw new Error(+ `[stateless-wake] Scenario 4 prewarm was skipped='${prewarmDuringColdWake.skipped}' ` ++ `(cooldown or in-flight collision with the app's own prewarm controller), so it ` ++ `returned no authoritative wake status. INDETERMINATE — never classified as warm. ` ++ `Raw prewarm payload: ${rawPrewarmA}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmDuringColdWake.status === 'wake-requested') {+ modeA = 'cold'+ } else if (prewarmDuringColdWake.status === 'active') {+ modeA = 'warm'+ } else {+ throw new Error(+ `[stateless-wake] Scenario 4 prewarm returned a non-classifiable status=` ++ `'${prewarmDuringColdWake.status}' (expected 'wake-requested' | 'active'). INDETERMINATE. ` ++ `Raw prewarm payload: ${rawPrewarmA}.`+ )+ }+ // Audit trail: emit the RAW prewarm response alongside the derived mode.+ await recordMode(testInfo, 'scenario-4-chat-a-cold-burst', modeA, {+ prewarm: {+ status: prewarmDuringColdWake.status,+ skipped: prewarmDuringColdWake.skipped,+ requested: prewarmDuringColdWake.requested,+ error: prewarmDuringColdWake.error,+ },+ })+ // Await the marker reply for continuity (chatIdA + the transcript legs below need+ // the turn to complete). resolveWakeOutcome covers both the transparent-warm and+ // the visible-waking-state retry paths; its return value is intentionally NOT the+ // mode oracle — the prewarm status above is authoritative.+ await resolveWakeOutcome(appPage, markerA)+ // Scenario 4 is the runtime proof of THIS PR's core contract — a CONCURRENT+ // session/model/message burst against a SUSPENDED host (the wake-displacement+ // fix). A warm burst proves nothing about it, so fail loud rather than record a+ // silent warm degrade. The FIXED idle above should have re-suspended the host;+ // a warm outcome means it stayed up.+ expect(+ modeA,+ `[stateless-wake] Scenario 4 cold burst took the WARM branch (prewarm status=` ++ `'${prewarmDuringColdWake.status}') after a fixed ` ++ `${Math.round(SCENARIO4_IDLE_RESUSPEND_MS / 1000)}s in-spec idle. This scenario ` ++ `must exercise the concurrent-on-COLD contract (replicas-0 wake-displacement). ` ++ `The aggressive HCC test cadences from the bash gate (idle floor 1m + drain + ` ++ `poll) must scale the host to 0 within that window; a warm burst means the host ` ++ `never re-suspended and the cold contract was NOT exercised. Idle window: ` ++ `${idleStartedAt} → ${idleEndedAt}.`+ ).toBe('cold')+ await expectComposerIdleReady(appPage, chatInput)+ const chatIdA = await readActiveChatId(appPage)++ // Chat B — a SECOND distinct conversation on the same agent (New chat again).+ // The host is warm now, so this send exercises the warm path.+ await openStatelessAgent(appPage)+ const markerB = `WAKE_S4_B_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerB}`)+ await sendButton.click()+ const modeB = await resolveWakeOutcome(appPage, markerB)+ await recordMode(testInfo, 'scenario-4-chat-b', modeB)+ await expectComposerIdleReady(appPage, chatInput)+ const chatIdB = await readActiveChatId(appPage)+ expect(chatIdA, 'the two chats must have distinct server identities').not.toBe(chatIdB)++ // B1 (a) — BEFORE the post-warm burst, assert BOTH chat identities are visible+ // in the "Latest sessions" region (not only through the RPC read). The region+ // renders only in the dedicated agent view, so navigate there first.+ let sessions = await openDedicatedAgentSessions(appPage)+ await expectSessionButtonVisible(sessions, chatIdA)+ await expectSessionButtonVisible(sessions, chatIdB)++ // Keep the RPC session read as the transport-level no-403 + identity proof.+ const before = await readStatelessSessionIds(appPage)+ expect(+ before.error,+ `[stateless-wake] listSessions must not 403 on wake — ${before.error}`+ ).toBeNull()+ const idsBefore = new Set(before.chatIds)+ expect(+ idsBefore.has(chatIdA) && idsBefore.has(chatIdB),+ 'both chat identities must surface in the server session list'+ ).toBe(true)++ // Reopen chat B (leaving the dedicated view) so the composer + model picker are+ // mounted for the warm-path burst and the SF3 model proof.+ await openExistingSession(appPage, sessions, chatIdB)++ // SF3 — the model list must be genuinely usable, not merely "did not 403".+ // Assert a positive model count over the wake-capable RPC AND drive the visible+ // model picker to prove selectable options render.+ const modelsWarm = await probeStatelessHostModels(appPage)+ expect(+ modelsWarm.error,+ `[stateless-wake] warm getHostModels must not fail — ${modelsWarm.error}`+ ).toBeNull()+ expect(+ modelsWarm.modelCount ?? 0,+ 'the stateless fixture host must expose at least one model on the warm path'+ ).toBeGreaterThan(0)+ await exerciseVisibleModelPicker(appPage)++ // Post-warm concurrent burst (kept — one warm turn): list sessions + load+ // models while a third send drives the composer, proving the wake-capable reads+ // stay 200 even while a send is in flight, and the send is not double-forwarded+ // (SF4).+ const markerC = `WAKE_S4_C_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerC}`)+ const [sessionsDuringWarm, modelsDuringWarm] = await Promise.all([+ readStatelessSessionIds(appPage),+ probeStatelessHostModels(appPage),+ sendButton.click(),+ ])+ expect(+ sessionsDuringWarm.error,+ `[stateless-wake] concurrent warm listSessions must not fail — ${sessionsDuringWarm.error}`+ ).toBeNull()+ expect(+ modelsDuringWarm.error,+ `[stateless-wake] concurrent warm getHostModels must not fail — ${modelsDuringWarm.error}`+ ).toBeNull()+ expect(+ new Set(sessionsDuringWarm.chatIds).size,+ 'concurrent listSessions must not drop either chat identity'+ ).toBeGreaterThanOrEqual(2)++ const modeC = await resolveWakeOutcome(appPage, markerC)+ await recordMode(testInfo, 'scenario-4-concurrent-warm', modeC)+ await expectComposerIdleReady(appPage, chatInput)++ // SF4 — no duplicate: the user's prompt AND the assistant's reply each render+ // exactly once in chat B's thread.+ const chatBList = appPage.getByTestId('message-list')+ await expect(chatBList.getByText(`Reply with exactly: ${markerC}`)).toHaveCount(1)+ await expect(chatBList.getByTestId('agent-response').filter({ hasText: markerC })).toHaveCount(1)++ // Step 9 + B1 (b) — navigate away to Agents and back into the dedicated sessions+ // view; assert BOTH identities are STILL visible in the session list.+ sessions = await openDedicatedAgentSessions(appPage)+ await expectSessionButtonVisible(sessions, chatIdA)+ await expectSessionButtonVisible(sessions, chatIdB)+ const after = await readStatelessSessionIds(appPage)+ expect(+ after.error,+ `[stateless-wake] post-navigation listSessions must not 403/fail — ${after.error}`+ ).toBeNull()+ const idsAfter = new Set(after.chatIds)+ for (const id of [chatIdA, chatIdB]) {+ expect(+ idsAfter.has(id),+ `Session identity ${id} must survive navigating away to Agents and back.`+ ).toBe(true)+ }++ // SF2 — transcript continuity through the VISIBLE UI: reopen chat A, then chat+ // B, and assert each earlier assistant reply is still rendered in message-list+ // (not merely chatId set-membership).+ await openExistingSession(appPage, sessions, chatIdA)+ await expectAssistantMarkerRendered(appPage, markerA)+ sessions = await openDedicatedAgentSessions(appPage)+ await openExistingSession(appPage, sessions, chatIdB)+ await expectAssistantMarkerRendered(appPage, markerB)+ await expectAssistantMarkerRendered(appPage, markerC)++ // §15.5 step 10 (SF5) — logout/login continuity: log out through the visible+ // settings menu, log back in as the SAME seeded user through the visible+ // email/password screen (loginAs → no Keychain, no storage injection), and+ // assert both identities and their transcript content survive the auth cycle.+ await logoutViaUi(appPage)+ await loginAs(appPage, E2E_EMAIL)+ sessions = await openDedicatedAgentSessions(appPage)+ await expectSessionButtonVisible(sessions, chatIdA)+ await expectSessionButtonVisible(sessions, chatIdB)+ await openExistingSession(appPage, sessions, chatIdA)+ await expectAssistantMarkerRendered(appPage, markerA)+ sessions = await openDedicatedAgentSessions(appPage)+ await openExistingSession(appPage, sessions, chatIdB)+ await expectAssistantMarkerRendered(appPage, markerB)++ // No unhandled wake dialog across the entire journey.+ expect(dialogs).toHaveLength(0)+ })++ // §15.5 step 11 — repeat one suspend/wake cycle to exclude a one-shot cache+ // artifact. This scenario runs ONLY in the bash gate's second Playwright pass+ // (grep "second cycle" + E2E_STATELESS_CYCLE=2), after force_idle_and_suspend has+ // suspended the host a SECOND time. On a fresh login it proves the chats created+ // in the first pass survived the second suspension (visible session list ++ // transcript) and that a fresh send wakes the host again and continues the same+ // thread.+ function requireSecondCyclePass(): void {+ if (STATELESS_CYCLE !== '2') {+ throw new Error(+ '[stateless-wake] E2E_STATELESS_CYCLE!=2 — the repeat suspend/wake cycle scenario must be ' ++ "driven by the bash gate's SECOND Playwright pass, after a second force_idle_and_suspend " ++ 're-suspends the host. Running it in the first pass would race a still-warm host and prove ' ++ 'nothing about a repeat cycle.'+ )+ }+ }++ test('Scenario 5 — repeat suspend/wake cycle keeps prior chats continuous (second cycle)', async ({+ appPage,+ }, testInfo) => {+ test.setTimeout(600_000)++ const dialogs: string[] = []+ appPage.on('dialog', dialog => {+ dialogs.push(dialog.message())+ void dialog.dismiss()+ })++ requireSecondCyclePass()+ requireSuspendPrecondition()++ // The chats from the first pass persist server-side across the second suspend.+ // Opening the dedicated session view serves the catalog through the wake-capable+ // read; a re-suspended host must therefore surface >= 2 prior sessions here+ // without a 403 or a false-empty catalog.+ const sessions = await openDedicatedAgentSessions(appPage)+ const priorIds = await readSessionButtonChatIds(sessions)+ expect(+ priorIds.length,+ 'the >=2 chats created in the first cycle must survive a SECOND suspend/wake'+ ).toBeGreaterThanOrEqual(2)++ const catalog = await readStatelessSessionIds(appPage)+ expect(+ catalog.error,+ `[stateless-wake] cycle-2 listSessions must not 403 on the re-suspended host — ${catalog.error}`+ ).toBeNull()+ expect(+ new Set(catalog.chatIds).size,+ 'the wake-capable session catalog must still report both prior chats after a second suspend'+ ).toBeGreaterThanOrEqual(2)++ // Reopen the first prior chat: its transcript (a prior assistant reply) must+ // still render — continuity BEFORE the measured second wake. This reopen is a+ // wake-capable read, so it (and the Playwright login/mount prewarm) may leave+ // the host warm; the in-spec re-suspension below restores a genuine replicas-0+ // state before the measured cold burst.+ const [targetChatId] = priorIds+ if (!targetChatId) {+ throw new Error('[stateless-wake] cycle-2 session catalog exposed no prior chat to reopen')+ }+ await openExistingSession(appPage, sessions, targetChatId)+ const messageList = appPage.getByTestId('message-list')+ const priorResponse = messageList.getByTestId('agent-response').first()+ await expect(+ priorResponse,+ 'a prior assistant reply must still render in the reopened chat after the second suspend'+ ).toBeVisible({ timeout: WAKE_VISIBLE_TIMEOUT })+ await expect(priorResponse).not.toHaveText('', { timeout: TURN_TIMEOUT })+ await expect(priorResponse).not.toHaveClass(/chat-bubble--error/)++ // Deliberate in-spec re-suspension, IDENTICAL to Scenario 4's established+ // pattern. The catalog + reopen reads above legitimately woke the host, and the+ // Playwright preflight/login/mount prewarm may already have warmed it, so+ // measuring the second wake right now would race a still-warm host (the cycle-2+ // warm-flake). Idle for a FIXED bounded window so the aggressive HCC test+ // cadences (idle floor 1m + drain + poll, set by the bash gate) scale the host+ // back to 0. No early probe send during the idle — a probe is itself a wake that+ // would burn the cold state. Log the window bounds so the orchestrator audit can+ // verify the idle actually elapsed. This makes the "repeat suspend/wake" cycle+ // the in-spec deterministic one, faithful to its own title.+ const idleStartedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-5-idle-resuspend',+ phase: 'start',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleStartedAt,+ })}`+ )+ await appPage.waitForTimeout(SCENARIO4_IDLE_RESUSPEND_MS)+ const idleEndedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-5-idle-resuspend',+ phase: 'end',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleEndedAt,+ })}`+ )++ // Drive the SECOND wake through the UI as a CONCURRENT cold burst on the FIRST+ // post-idle send into the SAME existing thread: the authoritative wake+ // (prewarmHost) races the send's own server-side reactive wake, exactly like+ // Scenario 4. Keep the click LAST. The prewarm 202 'wake-requested' is the+ // cold/warm oracle (control-api Postgres-backed); the UI waking-state affordance+ // is NOT used for the mode because a transparent sub-hold-deadline wake never+ // renders it.+ const chatInput = appPage.getByTestId('chat-input')+ const sendButton = appPage.getByRole('button', { name: /send message/i })+ const markerCycle2 = `WAKE_S5_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerCycle2}`)+ const [prewarmSecondCycle] = await Promise.all([+ probeStatelessPrewarm(appPage),+ sendButton.click(),+ ])++ // Authoritative cold/warm classification from the app's own prewarm response.+ // 'wake-requested' (202) proves the host was SUSPENDED at first touch; 'active'+ // (200) proves it was already warm. An error, a `skipped` (cooldown/in-flight),+ // or a missing/unknown status is INDETERMINATE — fail loud naming the reason and+ // the full raw payload, never silently classify warm.+ const rawPrewarm5 = JSON.stringify(prewarmSecondCycle)+ let mode: 'warm' | 'cold'+ if (prewarmSecondCycle.error) {+ throw new Error(+ `[stateless-wake] Scenario 5 prewarm oracle errored (${prewarmSecondCycle.error}); ` ++ `cannot classify the second-cycle wake. INDETERMINATE — not warm. Raw prewarm ` ++ `payload: ${rawPrewarm5}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmSecondCycle.skipped) {+ throw new Error(+ `[stateless-wake] Scenario 5 prewarm was skipped='${prewarmSecondCycle.skipped}' ` ++ `(cooldown or in-flight collision with the app's own prewarm controller), so it ` ++ `returned no authoritative wake status. INDETERMINATE — never classified as warm. ` ++ `Raw prewarm payload: ${rawPrewarm5}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmSecondCycle.status === 'wake-requested') {+ mode = 'cold'+ } else if (prewarmSecondCycle.status === 'active') {+ mode = 'warm'+ } else {+ throw new Error(+ `[stateless-wake] Scenario 5 prewarm returned a non-classifiable status=` ++ `'${prewarmSecondCycle.status}' (expected 'wake-requested' | 'active'). INDETERMINATE. ` ++ `Raw prewarm payload: ${rawPrewarm5}.`+ )+ }+ // Audit trail: emit the RAW prewarm response alongside the derived mode.+ await recordMode(testInfo, 'scenario-5-second-cycle', mode, {+ prewarm: {+ status: prewarmSecondCycle.status,+ skipped: prewarmSecondCycle.skipped,+ requested: prewarmSecondCycle.requested,+ error: prewarmSecondCycle.error,+ },+ })+ // Scenario 5 is the REPEAT suspend/wake proof: the second cycle must exercise a+ // genuine replicas-0 wake, not a warm no-op. Fail loud on a warm burst — it means+ // the fixed idle did not re-suspend the host and the repeat-cold contract was NOT+ // exercised.+ expect(+ mode,+ `[stateless-wake] Scenario 5 second-cycle burst took the WARM branch (prewarm status=` ++ `'${prewarmSecondCycle.status}') after a fixed ` ++ `${Math.round(SCENARIO4_IDLE_RESUSPEND_MS / 1000)}s in-spec idle. The repeat cycle must ` ++ `exercise a second replicas-0 wake; a warm burst means the host never re-suspended and ` ++ `the repeat-cold contract was NOT exercised. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ ).toBe('cold')+ // resolveWakeOutcome drives the transparent-warm / visible-waking-state retry and+ // verifies the marker reply completed; its return value is intentionally NOT the+ // mode oracle — the prewarm status above is authoritative.+ await resolveWakeOutcome(appPage, markerCycle2)+ await expectComposerIdleReady(appPage, chatInput)++ // Identity survives the SECOND wake too — continuity AFTER the measured cold wake.+ const afterWake = await readStatelessSessionIds(appPage)+ expect(+ afterWake.error,+ `[stateless-wake] post-second-wake listSessions must not 403/fail — ${afterWake.error}`+ ).toBeNull()+ const afterIds = new Set(afterWake.chatIds)+ for (const id of priorIds.slice(0, 2)) {+ expect(afterIds.has(id), `chat ${id} must survive the second suspend/wake cycle`).toBe(true)+ }++ expect(dialogs).toHaveLength(0)+ })diff --cc desktop-app/test/gfsAclShareFixtures.test.tsindex 000000000,3db3831d2..baad33750mode 000000,100644..100644--- a/desktop-app/test/gfsAclShareFixtures.test.ts+++ b/desktop-app/test/gfsAclShareFixtures.test.ts@@@ -1,0 -1,53 +1,52 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest'++import {++ getGfsTreeAclShareRows,++ seedIssue797SourceShare,++} from './e2e-playwright/helpers/gfsAclShareFixtures'++ const runControlPostgresSqlMock = vi.hoisted(() => vi.fn())++ vi.mock('../../tests/e2e/gfsUiFixtures', () => ({+ UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,+ runControlPostgresSql: runControlPostgresSqlMock,+ 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())++ it('seeds the named source share for a user, never a Host subject', () => {+ runControlPostgresSqlMock.mockReturnValue('d4d2c593-6932-488e-844c-c5852b910783\n')++ expect(+ seedIssue797SourceShare(+ '5a50453e-04d1-4403-8473-23013eaa56c7',+ 'ef72208d-783a-4574-9181-440a6764fa27'+ )+ ).toBe('d4d2c593-6932-488e-844c-c5852b910783')++ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])+ expect(sql).toContain("'user', 'ef72208d-783a-4574-9181-440a6764fa27'")+ expect(sql).toContain("ARRAY['read']::text[], true")+ expect(sql).not.toContain("'host'")+ })++ it('returns stable full-row JSON evidence for both grants and shares', () => {+ const rows = [+ '{"kind":"grant","row":{"id":"grant-1"}}',+ '{"kind":"share","row":{"id":"share-1"}}',+ ]+ runControlPostgresSqlMock.mockReturnValue(`\n${rows.join('\n')}\n`)++ expect(getGfsTreeAclShareRows('5a50453e-04d1-4403-8473-23013eaa56c7')).toEqual(rows)+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])+ expect(sql).toContain("jsonb_build_object('kind', 'grant', 'row', to_jsonb(g))")+ expect(sql).toContain("jsonb_build_object('kind', 'share', 'row', to_jsonb(s))")+ expect(sql).toContain('ORDER BY row_kind, row_id')+ })++ it('rejects an invalid root before querying PostgreSQL', () => {+ expect(() => getGfsTreeAclShareRows('not-a-resource-id')).toThrow('invalid GFS root id')+ expect(runControlPostgresSqlMock).not.toHaveBeenCalled()+ })+ })diff --cc desktop-app/test/gfsFixtureDiscovery.test.tsindex 000000000,e9f517c22..dd3e75c99mode 000000,100644..100644--- a/desktop-app/test/gfsFixtureDiscovery.test.ts+++ b/desktop-app/test/gfsFixtureDiscovery.test.ts@@@ -1,0 -1,74 +1,73 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import {++ discoverManagedGfsAgent,++ discoverManagedGfsAgents,++} from './e2e-playwright/helpers/gfsFixtures'++ const execFileSyncMock = vi.hoisted(() => vi.fn())++ 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: string++ beforeEach(() => {+ process.env.E2E_K8S_CONTEXT = context+ secretRows =+ 'host:1st:mcp-host/agent-a\tuid-a\t1\n' ++ 'host:1st:mcp-host/agent-b\tuid-b\t2\n' ++ 'host:1st:mcp-host/incomplete\t\t\n'+ execFileSyncMock.mockImplementation((_command: string, args: string[]) => {+ const resourceIndex = args.indexOf('get') + 1+ const resource = args[resourceIndex]+ if (resource === 'secrets') {+ return secretRows+ }+ if (resource === 'hosts' && args[resourceIndex + 1] === 'agent-a') {+ return 'uid-a\t1\t\t'+ }+ if (resource === 'hosts' && args[resourceIndex + 1] === 'agent-b') {+ return 'uid-b\t2\t\t'+ }+ throw new Error(`unexpected kubectl call: ${args.join(' ')}`)+ })+ })++ afterEach(() => {+ delete process.env.E2E_K8S_CONTEXT+ execFileSyncMock.mockReset()+ })++ it('reads only annotated Secret metadata and returns two active exact-subject hosts', () => {+ expect(discoverManagedGfsAgents()).toEqual([+ { name: 'agent-a', namespace: 'mcp-host', subjectId: '1st:mcp-host/agent-a' },+ { name: 'agent-b', namespace: 'mcp-host', subjectId: '1st:mcp-host/agent-b' },+ ])++ const calls = execFileSyncMock.mock.calls+ expect(calls).toHaveLength(3)+ for (const [command, args] of calls) {+ expect(command).toBe('kubectl')+ expect(args.slice(0, 2)).toEqual(['--context', context])+ }++ const secretArgs = calls[0]![1] as string[]+ const outputArg = secretArgs.find(value => value.startsWith('go-template='))+ expect(outputArg).toContain('{{with .metadata.annotations}}')+ expect(outputArg).toContain('clerum.io/gfs-token-expected-subject')+ expect(secretArgs).not.toContain('json')+ })++ it('keeps the single-agent read regression independent from the two-agent Copy gate', () => {+ secretRows = 'host:1st:mcp-host/agent-a\tuid-a\t1\n'++ expect(discoverManagedGfsAgent()).toEqual({+ name: 'agent-a',+ namespace: 'mcp-host',+ subjectId: '1st:mcp-host/agent-a',+ })+ })+ })diff --cc desktop-app/test/gfsUriHandler.test.tsindex d162a8f08,dac8fbd92..18d9442a5--- a/desktop-app/test/gfsUriHandler.test.ts+++ b/desktop-app/test/gfsUriHandler.test.ts@@@ -7,6 -8,6 +7,7 @@@ importparseGfsUri,parseSubjectKey,} from '../src/gfs/uriHandler.js'++import { ApiError } from '../src/httpClient.js'/*** P2-S06 — Desktop gfs:// resolve + read. Acceptance: a gfs://<drive>/<rid> linkdiff --cc desktop-app/test/rpcTokenManager.test.tsindex c5df4f1e7,4126151c4..7e603ad3c--- a/desktop-app/test/rpcTokenManager.test.ts+++ b/desktop-app/test/rpcTokenManager.test.ts@@@ -1,109 -1,157 +1,159 @@@- import { describe, it, expect, vi, beforeEach } from "vitest";-import { describe, it, expect, vi } from "vitest";----vi.mock("../src/config.js", () => ({-- config: { requestTimeoutMs: 5000, externalRestApiBaseUrl: "http://localhost:8091" },--}));--vi.mock("../src/httpClient.js", () => ({++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', () => ({requestJson: vi.fn(),-- ApiError: class extends Error { status = 0; bodyText = ""; },--}));----import { RpcTokenManager } from "../src/rpcTokenManager.js";--import type { AuthClient } from "../src/authClient.js";++ ApiError: class extends Error {++ status = 0++ bodyText = ''++ },++}))// ── 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);- });-- 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 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 ────────────────────────+ //+ // A narrower request is satisfied from a cached SUPERSET token, so the token a+ // caller receives can carry scopes it did not ask for — including+ // host:wake:write on a stream/observability surface. That is deliberate: it+ // keeps issuance to one round trip instead of one per distinct scope set, and+ // it is NOT a wake risk, because possessing the scope never wakes a Host —+ // rpc-proxy triggers a wake only from its explicit per-route allowlist plus the+ // isWakeCapable gate (wakeAndHold.ts).+ //+ // This test exists so the behavior is a pinned contract rather than an+ // 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 --cc desktop-app/ui/src/gfs/GfsGrantList/types.tsindex 000000000,18bc9cd87..727e5faabmode 000000,100644..100644--- a/desktop-app/ui/src/gfs/GfsGrantList/types.ts+++ b/desktop-app/ui/src/gfs/GfsGrantList/types.ts@@@ -1,0 -1,22 +1,22 @@@++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[]+ loading?: boolean+ /**+ * Mapped list-load failure. Severity 'quiet' (manage_acl_required) renders an+ * informational banner instead of the list; 'error' renders an error banner.+ */+ error?: GfsGrantErrorPresentation | null+ /** Label source for `host` subjects (the caller's own agents). */+ agents: GfsAgentSubjectOption[]+ /** Label source for `user`/`team` subjects (the visible team directory). */+ subjects: GfsDelegationSubjectOption[]+ onRevoke: (item: GfsGrantListItem, label: string) => void | Promise<void>+ revoking?: boolean+ }diff --cc desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsxindex 000000000,172f82176..3744df990mode 000000,100644..100644--- a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx@@@ -1,0 -1,125 +1,115 @@@+ // @vitest-environment jsdom+ import { afterEach, describe, expect, it, vi } from 'vitest'+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+ import { GfsAgentAccessSection } from '../GfsAgentAccessSection'++ /**+ * Per-agent GFS delegation section (Manage modal). Proves the read/write-only+ * permission cap, the `host:`-prefixed subject keys, and the inherit contract:+ * directories default inherit ON (a folder grant without inherit would silently+ * break the agent-reads-file journey); files never send inherit.+ */++ afterEach(cleanup)++ const agents = [+ { id: '1st:mcp-host/chatllm', name: 'chatllm' },+ { id: '1st:mcp-host/chatllm-stateless', name: 'chatllm-stateless' },+ ]++ 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()+ expect(screen.getByRole('menuitemcheckbox', { name: 'Write' })).toBeTruthy()+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Manage access' })).toBeNull()+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Share' })).toBeNull()+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Delete' })).toBeNull()+ })++ 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' }))+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))++ await waitFor(() =>+ expect(onGrantAgents).toHaveBeenCalledWith(+ ['host:1st:mcp-host/chatllm', 'host:1st:mcp-host/chatllm-stateless'],+ ['read'],+ true+ )+ )+ })++ 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)++ fireEvent.click(inherit)+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))++ await waitFor(() =>+ expect(onGrantAgents).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], false)+ )+ })++ it('hides the inherit toggle for files and always sends inherit false', async () => {+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)+ render(+ <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' }))++ await waitFor(() =>+ expect(onGrantAgents).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], false)+ )+ })++ it('surfaces a mapped server verdict and keeps ALL selected agents on an atomic failure', async () => {+ // The bulk grant is all-or-nothing: a rejection means NO agent was granted,+ // so every selected agent stays selected for a retry (no partial-success).+ 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' }))+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))++ await screen.findByText('Managed agents can only be granted read and write.')+ expect(onGrantAgents).toHaveBeenCalledTimes(1)+ expect(onGrantAgents).toHaveBeenCalledWith(+ ['host:1st:mcp-host/chatllm', 'host:1st:mcp-host/chatllm-stateless'],+ ['read'],+ 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')+ })++ it('renders an empty notice when the caller has no grantable agents', () => {+ render(<GfsAgentAccessSection agents={[]} isDirectory onGrantAgents={vi.fn()} />)++ expect(screen.getByText('You have no agents that can be granted access.')).toBeTruthy()+ expect(screen.queryByRole('button', { name: 'Grant agent access' })).toBeNull()+ })+ })diff --cc desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsxindex 000000000,ed69207c4..e9989c5a5mode 000000,100644..100644--- a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx@@@ -1,0 -1,119 +1,117 @@@+ // @vitest-environment jsdom+ import { afterEach, describe, expect, it, vi } from 'vitest'+ import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'-import type { GfsGrantListItem } from '../delegation.types'+ import { GfsGrantList } from '../GfsGrantList'++import type { GfsGrantListItem } from '../delegation.types'++ /**+ * "Who has access" list (Manage modal). Rows resolve host subjects to agent+ * names, user/team subjects through the visible team directory, and fall back+ * to the raw id (a row is never hidden). A manage_acl_required list failure is+ * an expected state and renders as a quiet informational banner, not an error.+ */++ afterEach(cleanup)++ const agents = [{ id: '1st:mcp-host/chatllm', name: 'Chat LLM' }]+ const subjects = [+ { type: 'user' as const, id: 'user-2', label: 'Test Two', description: '[email protected]' },+ { type: 'team' as const, id: 'team-1', label: 'Core Team' },+ ]++ function grantItem(overrides: Partial<GfsGrantListItem>): GfsGrantListItem {+ return {+ id: 'grant-1',+ drive: 'main',+ resourceId: 'res-1',+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },+ permissions: ['read'],+ inherit: false,+ ...overrides,+ }+ }++ describe('GfsGrantList', () => {+ it('renders resolved subject labels, permission chips, and the inherit badge', () => {+ render(+ <GfsGrantList+ agents={agents}+ items={[+ grantItem({ id: 'grant-1', permissions: ['read', 'write'], inherit: true }),+ grantItem({+ id: 'grant-2',+ subject: { type: 'user', id: 'user-2' },+ permissions: ['read'],+ }),+ grantItem({ id: 'grant-3', subject: { type: 'host', id: '1st:mcp-host/unknown' } }),+ ]}+ onRevoke={vi.fn()}+ subjects={subjects}+ />+ )++ const agentRow = screen.getByText('Chat LLM').closest('li')!+ expect(within(agentRow).getByText('Read')).toBeTruthy()+ expect(within(agentRow).getByText('Write')).toBeTruthy()+ expect(within(agentRow).getByText('Includes contents')).toBeTruthy()++ const userRow = screen.getByText('Test Two').closest('li')!+ expect(within(userRow).getByText('Read')).toBeTruthy()+ expect(within(userRow).queryByText('Includes contents')).toBeNull()++ // Unresolvable subject ids stay visible as raw ids — never hidden.+ expect(screen.getByText('1st:mcp-host/unknown')).toBeTruthy()+ })++ it('fires the revoke callback from the row button with an accessible name', () => {+ const onRevoke = vi.fn()+ const item = grantItem({ id: 'grant-1' })+ render(<GfsGrantList agents={agents} items={[item]} onRevoke={onRevoke} subjects={subjects} />)++ fireEvent.click(screen.getByRole('button', { name: 'Revoke access for Chat LLM' }))++ expect(onRevoke).toHaveBeenCalledWith(item, 'Chat LLM')+ })++ it('renders manage_acl_required as a quiet informational banner instead of the list', () => {+ render(+ <GfsGrantList+ agents={agents}+ error={{+ code: 'manage_acl_required',+ message: 'Only people with manage access can view who has access here.',+ severity: 'quiet',+ }}+ items={[grantItem({ id: 'grant-1' })]}+ onRevoke={vi.fn()}+ subjects={subjects}+ />+ )+- 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()+ })++ it('renders other list failures as an error banner', () => {+ render(+ <GfsGrantList+ agents={agents}+ error={{ code: null, message: 'listGrants exploded', severity: 'error' }}+ items={[]}+ onRevoke={vi.fn()}+ subjects={subjects}+ />+ )++ const banner = screen.getByText('listGrants exploded')+ expect(banner.closest('.status-banner')?.className).toContain('tone-error')+ })++ it('renders an empty notice when nothing has been granted', () => {+ render(<GfsGrantList agents={agents} items={[]} onRevoke={vi.fn()} subjects={subjects} />)++ expect(screen.getByText('No one has been granted access yet.')).toBeTruthy()+ })+ })diff --cc desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.tsindex 000000000,f2df6c2e8..1a3407e3fmode 000000,100644..100644--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts@@@ -1,0 -1,119 +1,115 @@@+ import { describe, expect, it } from 'vitest'+ import { describeGfsGrantError } from '../gfsGrantErrors'++ /**+ * Pure presentation map for GFS grant-plane server verdicts. Codes arrive+ * embedded in Electron IPC error messages, so matching is substring-based.+ *+ * `invalidIndexes` / `retryAfterSeconds` are SEPARATE response-body fields on the+ * server; the desktop main process (uriHandler surfaceGfsGrantError) appends them+ * to the error message as `invalidIndexes=[…]` / `retryAfterSeconds=…` BEFORE the+ * IPC boundary drops `ApiError.bodyText`. These cases feed that real production+ * message shape — not a JSON blob the wire never carries.+ */++ 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) => {+ const presentation = describeGfsGrantError(+ new Error(`Error invoking remote method 'gfs:grant': Error: 403 Forbidden: ${code}`)+ )++ expect(presentation).toEqual({ code, message, severity: 'error' })+ })++ 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({+ code: 'manage_acl_required',+ message: 'Only people with manage access can view who has access here.',+ severity: 'quiet',+ })+ })++ it('maps subjects_invalid without indexes', () => {+ expect(describeGfsGrantError(new Error('400 Bad Request: subjects_invalid'))).toEqual({+ code: 'subjects_invalid',+ message: 'Some selected subjects are invalid and were rejected.',+ severity: 'error',+ })+ })++ it('appends 1-based subject positions when subjects_invalid carries invalidIndexes', () => {+ // The exact message the main process now produces: the ApiError message with+ // the appended `invalidIndexes=[…]` the server sent as a separate body field.+ const presentation = describeGfsGrantError(+ new Error(+ "Error invoking remote method 'gfs:grant': Error: 400 Bad Request: subjects_invalid invalidIndexes=[0,2]"+ )+ )++ expect(presentation).toEqual({+ code: 'subjects_invalid',+ message: 'Some selected subjects are invalid and were rejected. (subjects 1, 3)',+ severity: 'error',+ })+ })++ it('maps 429 with retryAfterSeconds into the retry message', () => {+ // rate-limit body is `{ error: 'Too Many Requests', retryAfterSeconds }`; the+ // main process appends `retryAfterSeconds=…` from the dropped body field.+ const presentation = describeGfsGrantError(+ new Error(+ "Error invoking remote method 'gfs:grant': Error: 429 Too Many Requests: Too Many Requests retryAfterSeconds=42"+ )+ )++ expect(presentation).toEqual({+ code: 'rate_limited',+ message: 'Too many permission changes — try again in 42s.',+ severity: 'error',+ })+ })++ it('maps 429 without a parseable retryAfterSeconds to the generic retry message', () => {+ const presentation = describeGfsGrantError(new Error('429 Too Many Requests'))++ expect(presentation).toEqual({+ code: 'rate_limited',+ message: 'Too many permission changes — try again shortly.',+ severity: 'error',+ })+ })++ it('does not treat an id containing 429 as a rate limit', () => {+ const presentation = describeGfsGrantError(new Error('resource res-4290 not found'))++ expect(presentation).toEqual({+ code: null,+ message: 'resource res-4290 not found',+ severity: 'error',+ })+ })++ it('passes unknown errors through verbatim — fail loud, never swallow', () => {+ expect(describeGfsGrantError(new Error('total surprise'))).toEqual({+ code: null,+ message: 'total surprise',+ severity: 'error',+ })+ expect(describeGfsGrantError('string failure')).toEqual({+ code: null,+ message: 'string failure',+ severity: 'error',+ })+ })+ })diff --cc desktop-app/ui/src/pages/FilesPage.tsxindex f7f56e134,8e75585ae..8c9ed6df9--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@@ -15,11 -15,17 +15,17 @@@ importimport { desktopQueryKeys } from '@hooks/domain/queryKeys'import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'+ import { describeGfsGrantError } from '@lib/gfsGrantErrors'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'- import { GfsSubjectBatchError, runGfsSubjectBatch } from '@lib/gfsSubjectBatch'import { formatSharedFileSize } from '@lib/sharedFiles'- import { GfsDelegationPanel, type GfsDelegationSubjectOption } from '@/gfs/delegation'++import { GfsAgentAccessSection } from '@/gfs/GfsAgentAccessSection'++import { GfsGrantList } from '@/gfs/GfsGrantList'+ import {- GfsDelegationPanel,+ type GfsAgentSubjectOption,++ GfsDelegationPanel,+ 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'@@@ -129,6 -151,21 +151,18 @@@ export function FilesPage({ pushToast }() => delegationSubjectOptions(teamDirectoryQuery.data),[teamDirectoryQuery.data])+ // MY agents (with canonical gfsSubject) load when the Manage dialog opens:+ // they feed both the agent grant section and grant-list label resolution.+ const myAgentsQuery = useQuery({+ queryKey: desktopQueryKeys.myAgents,+ 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]+ )const canWriteCurrent = hasBit(affordances, 'write')const canDeleteCurrent = hasBit(affordances, 'delete')const currentIsFolder = current?.kind === 'directory'@@@ -949,6 -1004,24 +1001,26 @@@<p className="muted">Loading permissions…</p>)}</section>++ <section className="da-gfs-manage-section da-gfs-manage-section--grants">+ <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>+ <GfsGrantList+ agents={agentSubjects}+ error={grantsError}+ items={ctrl.grants}+ loading={ctrl.loadingGrants}+ onRevoke={(item, label) => void handleRevokeGrant(item.id, label)}+ revoking={ctrl.revoking}+ subjects={delegationSubjects}+ />+ </section></div></section></div>diff --cc desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 90ecb3093,5ef32fb7d..587080184--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@@ -710,6 -718,305 +718,302 @@@ describe('FilesPage', () =>expect(screen.queryByPlaceholderText(/uuid/i)).toBeNull()})+ it('loads my agents when the manage dialog opens and offers only valid gfs subjects', async () => {+ const listMine = vi.fn(async () => [+ {+ name: 'chatllm',+ contextRef: 'ctx-1',+ mcpServers: [],+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },+ },+ // No canonical gfsSubject yet — not a grantable delegation target.+ { name: 'pending-agent', contextRef: null, mcpServers: [] },+ ])+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ agents: { listMine },+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },+ },+ })+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder',+ name: 'Team folder',+ kind: 'directory',+ },+ affordances: {+ held: ['read', 'manage_acl'],+ canDelegate: true,+ grantableBits: ['read'],+ canCreateShare: false,+ },+ })++ renderFilesPage()+ expect(listMine).not.toHaveBeenCalled()++ await openManageDialog('Team folder')++ await waitFor(() => expect(listMine).toHaveBeenCalledTimes(1))+ expect(await screen.findByRole('button', { name: 'chatllm' })).toBeTruthy()+ expect(screen.queryByRole('button', { name: 'pending-agent' })).toBeNull()+ expect(+ screen.getByRole('checkbox', { name: 'Include contents of this folder' })+ ).toHaveProperty('checked', true)+ })++ it('refetches the grants list after a successful agent grant', async () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ agents: {+ listMine: vi.fn(async () => [+ {+ name: 'chatllm',+ contextRef: 'ctx-1',+ mcpServers: [],+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },+ },+ ]),+ },+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },+ },+ })+ const grant = vi.fn(async () => undefined)+ const refreshGrants = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder',+ name: 'Team folder',+ kind: 'directory',+ },+ affordances: {+ held: ['read', 'write', 'manage_acl'],+ canDelegate: true,+ grantableBits: ['read', 'write'],+ canCreateShare: false,+ },+ grant,+ refreshGrants,+ })++ renderFilesPage(pushToast)+ await openManageDialog('Team folder')++ fireEvent.click(await screen.findByRole('button', { name: 'chatllm' }))+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))++ await waitFor(() =>+ expect(grant).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], true)+ )+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 agent', 'success')+ })++ it('refetches the grants list after a successful user or team grant', async () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ agents: { listMine: vi.fn(async () => []) },+ team: {+ directory: vi.fn(async () => ({+ currentTeamId: 'team-1',+ items: [+ {+ team: { id: 'team-1', name: 'Core Team', role: 'admin' },+ members: [+ {+ id: 'user-2',+ email: '[email protected]',+ name: 'Test Two',+ role: 'member',+ status: 'active',+ },+ ],+ contextIds: [],+ agentNames: [],+ },+ ],+ })),+ },+ },+ })+ const grant = vi.fn(async () => undefined)+ const refreshGrants = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder',+ name: 'Team folder',+ kind: 'directory',+ },+ affordances: {+ held: ['read', 'manage_acl'],+ canDelegate: true,+ grantableBits: ['read'],+ canCreateShare: false,+ },+ grant,+ refreshGrants,+ })++ renderFilesPage(pushToast)+ await openManageDialog('Team folder')++ const subjectPicker = await screen.findByRole('combobox', { name: 'Add people or teams' })+ fireEvent.focus(subjectPicker)+ fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))+ fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))++ // handleGrant issues the grant then MUST list-after-write (the grant PUT+ // returns no ids). Deleting `await ctrl.refreshGrants()` must fail here.+ await waitFor(() => expect(grant).toHaveBeenCalledWith(['user:user-2'], ['read']))+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 subject', 'success')+ })++ it('issues ONE atomic bulk grant and does not refetch or toast when it is rejected', async () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ agents: { listMine: vi.fn(async () => []) },+ team: {+ directory: vi.fn(async () => ({+ currentTeamId: 'team-1',+ items: [+ {+ team: { id: 'team-1', name: 'Core Team', role: 'admin' },+ members: [+ {+ id: 'user-2',+ email: '[email protected]',+ name: 'Test Two',+ role: 'member',+ status: 'active',+ },+ {+ id: 'user-3',+ email: '[email protected]',+ name: 'Test Three',+ role: 'member',+ status: 'active',+ },+ ],+ contextIds: [],+ agentNames: [],+ },+ ],+ })),+ },+ },+ })+ // The bulk grant is atomic: the whole request is rejected, so NOTHING landed.+ // No success toast, and no list-after-write (there is nothing new to reveal).+ const grant = vi.fn().mockRejectedValue(new Error('400 Bad Request: subjects_invalid'))+ const refreshGrants = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder',+ name: 'Team folder',+ kind: 'directory',+ },+ affordances: {+ held: ['read', 'manage_acl'],+ canDelegate: true,+ grantableBits: ['read'],+ canCreateShare: false,+ },+ grant,+ refreshGrants,+ })++ renderFilesPage(pushToast)+ await openManageDialog('Team folder')++ const subjectPicker = await screen.findByRole('combobox', { name: 'Add people or teams' })+ fireEvent.focus(subjectPicker)+ fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))+ fireEvent.click(await screen.findByRole('option', { name: /Test Three/ }))+ fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))++ await waitFor(() =>+ expect(grant).toHaveBeenCalledWith(['user:user-2', 'user:user-3'], ['read'])+ )+ expect(grant).toHaveBeenCalledTimes(1)+ // 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 () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ agents: {+ listMine: vi.fn(async () => [+ {+ name: 'chatllm',+ contextRef: 'ctx-1',+ mcpServers: [],+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },+ },+ ]),+ },+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },+ },+ })+ const revokeGrant = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder',+ name: 'Team folder',+ kind: 'directory',+ },+ affordances: {+ held: ['read', 'manage_acl'],+ canDelegate: true,+ grantableBits: ['read'],+ canCreateShare: false,+ },+ grants: [+ {+ id: 'grant-1',+ drive: 'main',+ resourceId: 'folder-1',+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },+ permissions: ['read'],+ inherit: true,+ },+ ],+ revokeGrant,+ })++ renderFilesPage(pushToast)+ await openManageDialog('Team folder')++ fireEvent.click(await screen.findByRole('button', { name: 'Revoke access for chatllm' }))++ await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('grant-1'))+ await waitFor(() =>+ expect(pushToast).toHaveBeenCalledWith('Access revoked for chatllm', 'success')+ )+ })+it('refreshes server affordances whenever the manage dialog opens', async () => {const refreshAffordances = vi.fn(async () => undefined)hookMock.useGfsBrowserController.mockReturnValue({diff --cc host-context-controller/src/gfsConfig.tsindex f0a7b66f1,1c8760c14..331e43599--- a/host-context-controller/src/gfsConfig.ts+++ b/host-context-controller/src/gfsConfig.ts@@@ -60,8 -60,16 +60,13 @@@ export function gfsDefaultFactoryConfigjwtPublicKeyConfigMapKey: 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'),+ syncCopyMaxObjects: process.env.GFS_SYNC_COPY_MAX_OBJECTS,+ syncCopyMaxBytes: process.env.GFS_SYNC_COPY_MAX_BYTES,+ syncCopyTimeoutMs: process.env.GFS_SYNC_COPY_TIMEOUT_MS,nodeLocalDnsCidr: parseNodeLocalDnsCidr(env('CONTEXT_MAPPER_NODELOCAL_DNS_CIDR', '')),}}diff --cc host-context-controller/src/gfsHostSubject.test.tsindex 000000000,6de4b5e9a..68d1bfb09mode 000000,100644..100644--- a/host-context-controller/src/gfsHostSubject.test.ts+++ b/host-context-controller/src/gfsHostSubject.test.ts@@@ -1,0 -1,48 +1,45 @@@++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 = {+ label: string+ namespace: string+ name: string+ displayText: string+ expectedSubjectId: string | null+ expectedSubject: string | null+ }++ 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', () => {+ it.each(vectors)('matches the Control API identity contract: $label', vector => {+ const actual = makeExpectedHostGfsSubject(vector.namespace, vector.name)++ expect(actual).toBe(vector.expectedSubject)+ if (actual) {+ expect(actual).toBe(`host:${vector.expectedSubjectId}`)+ expect(actual).not.toContain(vector.displayText)+ }+ })++ it('does not accept display text in place of trusted metadata.name', () => {+ const vector = vectors.find(candidate => candidate.expectedSubject !== null)+ expect(vector).toBeDefined()+ expect(makeExpectedHostGfsSubject(vector!.namespace, vector!.displayText)).toBeNull()+ })++ it('reserves the legacy fleet-wide standalone subject without rejecting standalone elsewhere', () => {+ expect(makeExpectedHostGfsSubject('mcp-host', 'standalone')).toBeNull()+ expect(makeExpectedHostGfsSubject('sandbox-recipes', 'standalone')).toBe(+ 'host:1st:sandbox-recipes/standalone'+ )+ expect(makeExpectedHostGfsSubject('mcp-host', 'standalone-worker')).toBe(+ 'host:1st:mcp-host/standalone-worker'+ )+ })+ })diff --cc host-context-controller/src/hostReconciler.test.tsindex af87512ae,c6d258c89..495a4bc38--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@@ -10,10 -10,25 +10,29 @@@ importcreateMockNetworkingApi,createMockRbacApi,} from '../test/__fixtures__/testMocks'- import { HostFleetReconcileError, HostReconciler } from './hostReconciler'-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'+ function deferred<T = void>(): {+ promise: Promise<T>+ resolve: (value: T | PromiseLike<T>) => void+ reject: (reason?: unknown) => void+ } {+ let resolve!: (value: T | PromiseLike<T>) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+ }+vi.mock('./config', () => ({config: {hostNamespace: 'mcp-host',@@@ -387,35 -348,28 +352,34 @@@ describe('HostReconciler fleet failureconst internals = reconciler as unknown as {listManagedHostDeployments(): Promise<k8s.V1Deployment[]>deleteHostRuntimeResources(name: string, namespace: string): Promise<void>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>}- const firstOrphanFailure = new Error('first orphan cleanup failed')- const channelListFailure = new Error('channel-reader list failed')- const channelDeleteFailure = new Error('channel-reader delete failed')- const networkListFailure = new Error('NetworkPolicy list failed')- const channelSweepFailure = new AggregateError(- [channelListFailure, channelDeleteFailure],- 'channel-reader sweep failed'- )- const networkSweepFailure = new AggregateError(- [networkListFailure],- 'NetworkPolicy sweep failed'- )+ const orphanFailure = new Error('first orphan cleanup failed')vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([- { metadata: { name: 'orphan-a', namespace: 'mcp-host' } } as k8s.V1Deployment,- { metadata: { name: 'orphan-b', namespace: 'mcp-host' } } as k8s.V1Deployment,+ {+ 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,])- const deleteRuntime = vi+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources')- .mockRejectedValueOnce(firstOrphanFailure)+ .mockRejectedValueOnce(orphanFailure).mockResolvedValueOnce()- const channelSweep = vi- .spyOn(internals, 'sweepOrphanChannelReaderResources')- .mockRejectedValue(channelSweepFailure)- const networkPolicySweep = vi- .spyOn(internals, 'sweepOrphanHostNetworkPolicies')- .mockRejectedValue(networkSweepFailure)let thrown: unknowntry {@@@ -424,46 -378,203 +388,213 @@@thrown = error}- expect(deleteRuntime.mock.calls.map(([name]) => name)).toEqual(['orphan-a', 'orphan-b'])- expect(channelSweep).toHaveBeenCalledWith([])- expect(networkPolicySweep).toHaveBeenCalledWith([])- expect(thrown).toBeInstanceOf(AggregateError)- expect((thrown as AggregateError).errors).toEqual([- firstOrphanFailure,- channelSweepFailure,- networkSweepFailure,- ])- expect(channelSweepFailure.errors).toEqual([channelListFailure, channelDeleteFailure])- expect(networkSweepFailure.errors).toEqual([networkListFailure])- })-- it('continues every channel-reader resource sweep and aggregates non-404 failures', async () => {- const deploymentListFailure = new Error('Deployment list failed')- const serviceDeleteFailure = new Error('Service delete failed')- const secretListFailure = new Error('Secret list failed')- const appsApi = createMockAppsApi()- appsApi.listNamespacedDeployment.mockRejectedValue(deploymentListFailure)- const coreApi = Object.assign(createMockCoreApi(), {- listNamespacedService: vi.fn().mockResolvedValue({- items: [- {+ expect(del.mock.calls.map(([name]) => name).sort()).toEqual(['orphan-a', 'orphan-b'])+ expect(getObj).toHaveBeenCalledTimes(2)+ expect(thrown).toBeInstanceOf(HostFleetReconcileError)+ expect((thrown as HostFleetReconcileError).cleanupFailures).toContain(orphanFailure)+ })+ })++ /**+ * Current value of clerum_hcc_host_delete_cleanup_total for one `outcome`+ * label. Read from the live HCC registry (metrics are NOT mocked here), so a+ * skip that fails to record is caught rather than passing silently.+ */+ async function readHostDeleteCleanupOutcome(outcome: string): Promise<number> {+ const metric = registry.getSingleMetric('clerum_hcc_host_delete_cleanup_total')+ if (!metric) throw new Error('clerum_hcc_host_delete_cleanup_total is not registered')+ const snapshot = await metric.get()+ const match = snapshot.values.find(entry => entry.labels.outcome === outcome)+ return match?.value ?? 0+ }++ function makeCleanupReconciler(customApi: { getNamespacedCustomObject: ReturnType<typeof vi.fn> }) {+ return new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ customApi: customApi as unknown as k8s.CustomObjectsApi,+ })+ }++ describe('HostReconciler bounded fleet workers', () => {+ it('admits at most the configured number of Host reconciles concurrently', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ 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 = 0+ let maxActive = 0+ const gates: Array<() => void> = []+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1+ })+ const hosts = ['h1', 'h2', 'h3', 'h4'].map(name => makeHost({ name }))+ const pass = reconciler.fullReconcile(hosts)++ // Only two workers may run at once; the pool must not admit h3/h4 yet.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ // Drain: each release lets the pool admit the next queued Host key.+ for (let i = 0; i < hosts.length; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()+ }+ await pass+ expect(maxActive).toBe(2)+ })++ it('keeps urgent per-Host events outside the fleet worker budget', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ 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 = 0+ let maxActive = 0+ const gates = new Map<string, () => void>()+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async host => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.set(host.name, resolve))+ active -= 1+ })+ const fleetHosts = ['f1', 'f2', 'f3', 'f4'].map(name => makeHost({ name }))+ const pass = reconciler.fullReconcile(fleetHosts)+ await vi.waitFor(() => expect(gates.size).toBe(2)) // fleet budget saturated++ // An urgent event for an unrelated Host must still be admitted immediately,+ // even though the fleet workers already occupy the whole budget.+ const urgent = reconciler.reconcile(makeHost({ name: 'urgent' }), 'urgent')+ await vi.waitFor(() => expect(gates.has('urgent')).toBe(true))+ expect(maxActive).toBe(3) // 2 fleet + 1 urgent++ // Drain repeatedly so the remaining fleet workers (f3/f4) are admitted and+ // released as earlier ones finish.+ const settled = Promise.all([pass, urgent])+ for (let i = 0; i < 12; i++) {+ for (const [name, resolve] of [...gates]) {+ gates.delete(name)+ resolve()+ }+ await Promise.resolve()+ await Promise.resolve()+ }+ await settled+ })+ })++ describe('HostReconciler lifecycle-only vs full pass cleanup boundary', () => {+ it('reconcileHosts (lifecycle-only) runs NO orphan cleanup; fullReconcile does', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ const internals = reconciler as unknown as {+ collectHostReconcileFailures(...args: unknown[]): Promise<unknown[]>+ collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>+ }+ const reconcileFailures = vi+ .spyOn(internals, 'collectHostReconcileFailures')+ .mockResolvedValue([])+ const cleanup = vi.spyOn(internals, 'collectHostCleanupFailures').mockResolvedValue([])++ // The lifecycle-only pass is what CommunicationChannel recovery and the+ // heartbeat-driven fleet convergence dispatch through (k8sClient+ // reconcileHosts()). It MUST NOT run destructive orphan cleanup: a+ // lifecycle pass whose watch authority is stale could otherwise delete a+ // just-created Host's children (Risk register: "Stale full pass deletes a+ // new Host's resources" — critical). Only the authoritative full pass,+ // which captures watch authority up front, is allowed to clean up.+ await reconciler.reconcileHosts([makeHost({ name: 'h1' })])+ expect(reconcileFailures).toHaveBeenCalledTimes(1)+ expect(cleanup).not.toHaveBeenCalled()++ // The authoritative full pass is the ONLY caller that runs orphan cleanup.+ await reconciler.fullReconcile([makeHost({ name: 'h1' })])+ expect(cleanup).toHaveBeenCalledTimes(1)+ })+ })++ describe('HostReconciler bounded orphan cleanup (Addendum 2)', () => {+ it('deletes orphan bundles through the bounded worker pool, never an unbounded fan-out', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined) // every candidate is an orphan+ const internals = reconciler as unknown as {+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue(+ ['orphan-a', 'orphan-b', 'orphan-c', 'orphan-d'].map(+ name =>+ ({metadata: {- name: 'channel-reader-orphan',+ name,+ namespace: 'mcp-host',labels: {- app: 'channel-reader','clerum.io/managed-by': 'host-context-controller',- 'clerum.io/host': 'orphan',+ 'clerum.io/host': name,},},- },- ],- }),+ }) as k8s.V1Deployment+ )+ )+ let active = 0+ let maxActive = 0+ const gates: Array<() => void> = []+ vi.spyOn(internals, 'deleteHostRuntimeResources').mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1})- coreApi.deleteNamespacedService.mockRejectedValue(serviceDeleteFailure)- coreApi.listNamespacedSecret.mockRejectedValue(secretListFailure)++ const pass = reconciler.fullReconcile([])++ // Bound = HCC_HOST_FULL_RECONCILE_CONCURRENCY (2): only two orphan bundles+ // delete at once; the pool must not admit orphan-c/orphan-d yet.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ for (let i = 0; i < 4; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()+ }+ await pass+ expect(maxActive).toBe(2)+ })+ })++ describe('HostReconciler bounded channel-reader revision fan-out (Addendum 2)', () => {+ it('patches every affected Host through the bounded worker pool', async () => {const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(appsApi),- coreApi: asCoreApi(coreApi),+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),})diff --cc host-context-controller/src/hostReconciler.tsindex c6ca15041,c9251dece..5bf92cfa6--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@@ -19,6 -21,6 +21,13 @@@ 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,@@@ -3643,217 -3886,320 +3886,324 @@@ export class HostReconciler)}- async reconcileDelete(name: string, namespace: string): Promise<void> {- await this.deleteHostRuntimeResources(name, namespace)- this.clearStatus(name)- this.desktopHosts.delete(name)+ /**+ * Delete a Host's runtime bundle.+ *+ * `opts.skipIf` is an OPTIONAL fence evaluated INSIDE the per-Host serializer,+ * immediately before anything destructive runs. Callers whose "this Host is+ * gone" decision was made BEFORE admission (the watch-recovery diff, which+ * compares LIST-time names) pass it so a same-name Host recreated during the+ * admission window is not wiped: the recreation's ADDED sets the cache and+ * enters this Host's chain FIRST, its reconcile rebuilds the bundle, and only+ * then does the stale delete reach the front of the strict-FIFO queue.+ * Ownership labels cannot discriminate here — the rebuilt bundle carries+ * identical `clerum.io/host` + managed-by labels — and no uid is available on+ * that path, so cache presence at admission is the correct fence. This+ * mirrors the F2/#827 in-serializer re-check in collectHostCleanupFailures.+ *+ * Callers that omit `opts` keep the previous unconditional behavior exactly.+ */+ async reconcileDelete(+ name: string,+ namespace: string,+ opts?: { skipIf?: () => boolean }+ ): Promise<void> {+ // A DELETED event must not race an in-flight create/update for the same+ // Host: route it through the same per-Host serializer as reconcile(). The+ // global convergence tail no longer provides this ordering.+ await this.lifecycle.serializeByHost(name, async () => {+ if (opts?.skipIf?.()) {+ // Same vocabulary the watch path already reports for this condition+ // (reconcileHostWatchEvent), so the skip is observable, not silent.+ hostDeleteCleanupTotal.inc({ outcome: 'superseded' })+ return+ }+ await this.deleteHostRuntimeResources(name, namespace)+ this.clearStatus(name)+ this.desktopHosts.delete(name)+ })}- private async collectHostReconcileFailures(desiredHosts: HostCRD[]): Promise<unknown[]> {- const failures: unknown[] = []- for (const host of desiredHosts) {+ /**+ * Reconcile the fleet with bounded cross-Host concurrency. Dispatches Host+ * KEYS (not stale object snapshots): each worker resolves the CURRENT cached+ * Host at execution time and skips entries the cache no longer holds+ * (superseded by a delete/newer event). Failures are aggregated completely.+ */+ private async collectHostReconcileFailures(+ desiredHosts: HostCRD[],+ source: HostReconcileSource+ ): Promise<unknown[]> {+ const snapshotByName = new Map(desiredHosts.map(h => [h.name, h]))+ const resolve = this.resolveCurrentHost ?? ((name: string) => snapshotByName.get(name))+ const keys = desiredHosts.map(h => h.name)+ return runBoundedHostWorkers(keys, config.hostFullReconcileConcurrency, async name => {+ const host = resolve(name)+ if (!host) return // absent/superseded since the pass captured its snapshottry {- await this.reconcile(host)+ await this.reconcile(host, source)} catch (error) {- console.error(`[HostReconciler] Fleet reconcile failed for Host "${host.name}":`, error)- failures.push(error)+ console.error(`[HostReconciler] Fleet reconcile failed for Host "${name}":`, error)+ throw error}- }- return failures+ })}- private async collectHostCleanupFailures(desiredHosts: HostCRD[]): Promise<unknown[]> {+ /**+ * Orphan cleanup with the §10.5 authority contract (replaces the accidental+ * safety the removed global tail used to provide):+ * - runs only with known watch authority and the SAME generation captured at+ * pass start;+ * - compares candidates with the CURRENT cache, not the pass snapshot;+ * - groups candidates by owning logical Host from ownership labels; a+ * candidate with no derivable owner is NEVER deleted (deferred + recorded);+ * - performs ONE fresh authoritative Host read per orphan Host; a confirmed+ * 404 (while authority stays valid) authorizes deleting that Host's entire+ * owned bundle INSIDE the Host's per-Host serializer;+ * - defers (with a bounded reason) on unknown authority, generation drift,+ * watch loss, a present read, or a failed read.+ */+ private async collectHostCleanupFailures(+ capturedAuthority: HostWatchAuthoritySnapshot+ ): Promise<unknown[]> {const failures: unknown[] = []- let existingDeployments: k8s.V1Deployment[] = []+ const authorityValid = (): boolean => {+ const current = this.hostWatchAuthority()+ return (+ capturedAuthority.known &&+ current.known &&+ capturedAuthority.generation === current.generation+ )+ }++ 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+ }++ let candidates: CleanupCandidate[]try {- existingDeployments = await this.listManagedHostDeployments()+ candidates = await this.gatherCleanupCandidates(failures)} catch (error) {- console.error('[HostReconciler] Failed to list managed host deployments:', error)failures.push(error)+ return failures}- const desiredNames = new Set(desiredHosts.map(h => h.name))- for (const deployment of existingDeployments) {- const name = deployment.metadata?.name || ''- const namespace = deployment.metadata?.namespace || config.hostNamespace- if (!desiredNames.has(name)) {- try {- await this.deleteHostRuntimeResources(name, namespace)- } catch (error) {- console.error(`[HostReconciler] Fleet cleanup failed for orphan Host "${name}":`, error)- failures.push(error)- }++ const cacheHasHost = (name: string): boolean =>+ this.resolveCurrentHost ? this.resolveCurrentHost(name) !== undefined : false++ const orphanHosts = new Set<string>()+ for (const candidate of candidates) {+ if (!candidate.owner) {+ // Never delete a resource whose owning Host cannot be derived.+ hostCleanupDeferredTotal.inc({ reason: 'no_owner_label' })+ console.warn(+ `[HostReconciler] Deferring orphan candidate ${candidate.kind}/${candidate.name}: no derivable owning Host`+ )+ continue}+ if (cacheHasHost(candidate.owner)) continue // still present → retain+ orphanHosts.add(candidate.owner)}- const knownHostNames = desiredHosts.map(h => h.name)- for (const sweep of [- () => this.sweepOrphanChannelReaderResources(knownHostNames),- () => this.sweepOrphanHostNetworkPolicies(knownHostNames),- ]) {- try {- await sweep()- } catch (error) {- failures.push(error)+ // §10.5 destructive cleanup runs per orphan logical Host. Each Host's owned+ // write set is disjoint (§10.4 inventory) and each destructive bundle runs+ // inside that Host's own `serializeByHost` chain, so distinct orphan Hosts+ // are provably independent. Addendum 2: dispatch them through the same+ // bounded worker pool as the fleet (reusing HCC_HOST_FULL_RECONCILE_CONCURRENCY)+ // instead of a serial `for … await` — never an unbounded fan-out at the K8s+ // API. Same-Host ordering is still guaranteed by serializeByHost, and delete+ // failures still aggregate completely because runBoundedHostWorkers collects+ // every lane's throw.+ const cleanupFailures = await runBoundedHostWorkers(+ Array.from(orphanHosts),+ config.hostFullReconcileConcurrency,+ async hostName => {+ if (!authorityValid()) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ console.warn(+ `[HostReconciler] Deferring orphan cleanup for "${hostName}": watch authority lost`+ )+ return+ }+ const presence = await this.readHostPresence(hostName)+ if (presence === 'present') return // reappeared → retain+ if (presence === 'error') {+ hostCleanupDeferredTotal.inc({ reason: 'fresh_read_failed' })+ return+ }+ if (+ !destructiveCleanupAllowed({+ watchAuthorityKnown: this.hostWatchAuthority().known,+ capturedWatchGeneration: capturedAuthority.generation,+ currentWatchGeneration: this.hostWatchAuthority().generation,+ currentCacheOmitsHost: !cacheHasHost(hostName),+ // Derived, not hardcoded. `presence` is provably 'absent' here (the+ // 'present' and 'error' branches returned above), so this evaluates+ // to the identical literal and the runtime behavior is unchanged.+ // Deriving it makes the mapping total: if readHostPresence ever+ // grows a fourth outcome, the else-branch type stops satisfying+ // freshAuthoritativeRead's union and the compiler rejects it —+ // instead of silently labelling a non-404 read as 'confirmed404'+ // in a value that is DECISIONAL (a conjunct of+ // destructiveCleanupAllowed, :94-95), not telemetry.+ freshAuthoritativeRead: presence === 'absent' ? 'confirmed404' : presence,+ })+ ) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ return+ }+ try {+ await this.lifecycle.serializeByHost(hostName, async () => {+ // F2 / #827 TOCTOU: a same-name Host recreated between the fresh read+ // above and admission into this serializer updates the current cache+ // (its ADDED event sets the cache before its reconcile runs, and that+ // reconcile serializes ahead of this delete). Re-check the current+ // cache INSIDE the serializer so a just-recreated Host's bundle is+ // never deleted by this stale cleanup.+ if (cacheHasHost(hostName)) {+ hostCleanupDeferredTotal.inc({ reason: 'recreated' })+ return+ }+ await this.deleteHostRuntimeResources(hostName, config.hostNamespace)+ })+ } catch (error) {+ console.error(+ `[HostReconciler] Fleet cleanup failed for orphan Host "${hostName}":`,+ error+ )+ throw error+ }}- }+ )+ failures.push(...cleanupFailures)return failures}- async reconcileHosts(desiredHosts: HostCRD[]): Promise<void> {- const hostFailures = await this.collectHostReconcileFailures(desiredHosts)- if (hostFailures.length > 0) {- throw new HostFleetReconcileError(hostFailures, [])+ /**+ * List every managed resource that could be an orphan and derive its owning+ * logical Host from ownership labels. List failures are collected into+ * `listFailures` (reported by the caller) so a partial discovery still cleans+ * what it could confidently attribute. Candidates never drive a delete on+ * their own — the caller applies the fresh-read authority gate.+ */+ private async gatherCleanupCandidates(listFailures: unknown[]): Promise<CleanupCandidate[]> {+ const candidates: CleanupCandidate[] = []+ const pushOwner = (kind: string, name: string | undefined, owner: string | undefined): void => {+ if (!name) return+ candidates.push({ kind, name, owner })}- }- async fullReconcile(desiredHosts: HostCRD[]): Promise<void> {- const hostFailures = await this.collectHostReconcileFailures(desiredHosts)- const cleanupFailures = await this.collectHostCleanupFailures(desiredHosts)- if (hostFailures.length > 0 || cleanupFailures.length > 0) {- throw new HostFleetReconcileError(hostFailures, cleanupFailures)+ try {+ for (const deployment of await this.listManagedHostDeployments()) {+ pushOwner(+ 'Deployment',+ deployment.metadata?.name,+ deployment.metadata?.labels?.[HOST_LABEL]+ )+ }+ } catch (error) {+ console.error('[HostReconciler] Failed to list managed host deployments:', error)+ listFailures.push(error)}- }-- private async listManagedHostDeployments(): Promise<k8s.V1Deployment[]> {- const response = await this.appsApi.listNamespacedDeployment({- namespace: config.hostNamespace,- labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- })- return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])- }- /**- * Sweep orphan channel-reader resources from the channels namespace.- * Lists Deployments and Secrets carrying our management labels, then- * deletes those whose clerum.io/host label points at a Host that no- * longer exists. Catches CRDs deleted while HCC was down (UI cascade- * may have been skipped or interrupted).- */- private async sweepOrphanChannelReaderResources(knownHosts: string[]): Promise<void> {- const known = new Set(knownHosts)- const ns = config.channelsNamespace- const failures: unknown[] = []-- // Deployment sweep+ const channelsNs = config.channelsNamespace+ const managed = (labels: Record<string, string> | undefined): boolean =>+ labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUEtry {- const list = await this.appsApi.listNamespacedDeployment({ namespace: ns })+ const list = await this.appsApi.listNamespacedDeployment({ namespace: channelsNs })for (const dep of list.items ?? []) {- const labels = dep.metadata?.labels ?? {}- if (labels.app !== 'channel-reader') continue- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = dep.metadata?.name- if (!name) continue- try {- await this.appsApi.deleteNamespacedDeployment({- name,- namespace: ns,- })- console.log(`[HostReconciler] orphan sweep deleted Deployment ${name}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Deployment delete failed:`, err)- failures.push(err)- }- }+ const labels = dep.metadata?.labels+ if (labels?.app !== 'channel-reader' || !managed(labels)) continue+ pushOwner('ChannelReaderDeployment', dep.metadata?.name, labels[HOST_LABEL])}- } catch (err) {- console.warn('[HostReconciler] orphan Deployment sweep list failed:', err)- failures.push(err)+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Deployment candidate list failed:', error)+ listFailures.push(error)}-- // Service sweeptry {- const list = await this.coreApi.listNamespacedService({ namespace: ns })+ const list = await this.coreApi.listNamespacedService({ namespace: channelsNs })for (const svc of list.items ?? []) {- const labels = svc.metadata?.labels ?? {}- if (labels.app !== 'channel-reader') continue- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = svc.metadata?.name- if (!name) continue- try {- await this.coreApi.deleteNamespacedService({- name,- namespace: ns,- })- console.log(`[HostReconciler] orphan sweep deleted Service ${name}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Service delete failed:`, err)- failures.push(err)- }- }+ const labels = svc.metadata?.labels+ if (labels?.app !== 'channel-reader' || !managed(labels)) continue+ pushOwner('ChannelReaderService', svc.metadata?.name, labels[HOST_LABEL])}- } catch (err) {- console.warn('[HostReconciler] orphan Service sweep list failed:', err)- failures.push(err)- }-- // Secret sweep — server-side label filter limits the list response to- // Secrets HCC created. The channels-namespace Role grants `secrets: delete`- // broadly because K8s RBAC has no resourceName wildcards, but the actual- // operation here only ever sees managed Secrets, and the in-loop label- // guard below is a defense-in-depth check against any future code path- // that drops the labelSelector.- const sweepLabelSelector = [- `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- 'clerum.io/component=channel-reader',- ].join(',')+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Service candidate list failed:', error)+ listFailures.push(error)+ }try {const list = await this.coreApi.listNamespacedSecret({- namespace: ns,- labelSelector: sweepLabelSelector,+ 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 ?? {}- // Belt-and-suspenders: re-verify the managed-by + component labels- // even though the labelSelector should already have filtered them.- // If a future bug drops the selector, this prevents an unscoped- // delete sweep across the channels namespace.- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- if (labels['clerum.io/component'] !== 'channel-reader') continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = sec.metadata?.name- if (!name) continue- try {- await this.coreApi.deleteNamespacedSecret({- name,- namespace: ns,- })- // Structured audit line — every Secret deletion HCC performs.- // Operators tail this to monitor unexpected deletes.- console.log(- `[HostReconciler] AUDIT: orphan sweep deleted Secret name=${name} ns=${ns} host=${host}`- )- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Secret delete failed:`, err)- failures.push(err)- }+ const labels = sec.metadata?.labels+ if (!managed(labels) || labels?.['clerum.io/component'] !== 'channel-reader') continue+ pushOwner('ChannelReaderSecret', sec.metadata?.name, labels[HOST_LABEL])+ }+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Secret candidate list failed:', error)+ listFailures.push(error)+ }++ // #827 (Addendum 4 item 4): partial-leftover discovery. A bundle whose+ // Deployment — and even its NetworkPolicies — are already gone must still be+ // discovered from ANY surviving owned resource. List every owned kind HCC+ // writes in the host namespace by ownership label and derive the owner from+ // clerum.io/host; a candidate without a derivable owner is never deleted by+ // the caller (§10.5).+ const hostNs = config.hostNamespace+ const managedSelector = `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`+ const gatherOwnedKind = async (+ kind: string,+ list: () => Promise<{+ items?: Array<{ metadata?: { name?: string; labels?: Record<string, string> } }>+ }>+ ): Promise<void> => {+ try {+ const res = await list()+ for (const item of res.items ?? []) {+ if (!managed(item.metadata?.labels)) continue+ pushOwner(kind, item.metadata?.name, item.metadata?.labels?.[HOST_LABEL])}+ } catch (error) {+ console.warn(`[HostReconciler] ${kind} candidate list failed in ${hostNs}:`, error)+ listFailures.push(error)}- } catch (err) {- console.warn('[HostReconciler] orphan Secret sweep list failed:', err)- failures.push(err)}- throwCleanupFailures(failures, 'Failed to sweep orphan channel-reader resources')- }+ await gatherOwnedKind('Service', () =>+ this.coreApi.listNamespacedService({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('PersistentVolumeClaim', () =>+ this.coreApi.listNamespacedPersistentVolumeClaim({+ namespace: hostNs,+ labelSelector: managedSelector,+ })+ )+ await gatherOwnedKind('ServiceAccount', () =>+ this.coreApi.listNamespacedServiceAccount({+ namespace: hostNs,+ labelSelector: managedSelector,+ })+ )+ await gatherOwnedKind('Secret', () =>+ this.coreApi.listNamespacedSecret({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('Role', () =>+ this.rbacApi.listNamespacedRole({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('RoleBinding', () =>+ this.rbacApi.listNamespacedRoleBinding({ namespace: hostNs, labelSelector: managedSelector })+ )- /**- * Sweep orphan per-Host NetworkPolicies in both `channels` and `mcp-host`- * namespaces. Lists NPs carrying our managed-by label, deletes those whose- * clerum.io/host points at a Host that no longer exists.- *- * Filter is `clerum.io/managed-by=host-context-controller` — leaves the- * static base policies (no managed-by label) untouched.- */- private async sweepOrphanHostNetworkPolicies(knownHosts: string[]): Promise<void> {- const known = new Set(knownHosts)- const failures: unknown[] = []for (const ns of [config.channelsNamespace, config.hostNamespace, config.rpcProxyNamespace]) {try {const list = await this.networkingApi.listNamespacedNetworkPolicy({@@@ -3861,28 -4207,67 +4211,66 @@@labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,})for (const np of list.items ?? []) {- const labels = np.metadata?.labels ?? {}- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = np.metadata?.name- if (!name) continue- try {- await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })- console.log(`[HostReconciler] orphan sweep deleted NetworkPolicy ${name} in ${ns}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan NP delete failed:`, err)- failures.push(err)- }- }+ pushOwner('NetworkPolicy', np.metadata?.name, np.metadata?.labels?.[HOST_LABEL])}- } catch (err) {- console.warn(`[HostReconciler] orphan NP sweep list failed in ${ns}:`, err)- failures.push(err)+ } catch (error) {+ console.warn(`[HostReconciler] NetworkPolicy candidate list failed in ${ns}:`, error)+ listFailures.push(error)}}- throwCleanupFailures(failures, 'Failed to sweep orphan Host NetworkPolicies')++ return candidates+ }++ /**+ * One fresh authoritative Host read. `absent` is a confirmed 404 (the Host is+ * genuinely gone). `present` means the Host reappeared. `error` (timeout,+ * forbidden, 5xx) is deliberately NOT surfaced as a pass failure — the caller+ * defers with a bounded reason, matching the §13.2 cleanup matrix.+ */+ private async readHostPresence(name: string): Promise<'absent' | 'present' | 'error'> {+ try {+ await this.customApi.getNamespacedCustomObject({+ group: HOST_GROUP,+ version: HOST_VERSION,+ namespace: config.hostNamespace,+ plural: HOST_PLURAL,+ name,+ })+ return 'present'+ } catch (error) {+ if (getErrorCode(error) === 404) return 'absent'+ console.warn(`[HostReconciler] Fresh authoritative read for orphan "${name}" failed:`, error)+ return 'error'+ }+ }++ async reconcileHosts(desiredHosts: HostCRD[]): Promise<void> {+ const hostFailures = await this.collectHostReconcileFailures(desiredHosts, 'fleet')+ if (hostFailures.length > 0) {+ throw new HostFleetReconcileError(hostFailures, [])+ }+ }++ async fullReconcile(desiredHosts: HostCRD[]): Promise<void> {+ // Capture watch authority + generation at pass start (§10.5 step 1) so+ // cleanup can prove nothing shifted underneath it before deleting.+ const capturedAuthority = this.hostWatchAuthority()+ const hostFailures = await this.collectHostReconcileFailures(desiredHosts, 'fleet')+ // Cleanup runs only after every fleet worker has settled.+ const cleanupFailures = await this.collectHostCleanupFailures(capturedAuthority)+ if (hostFailures.length > 0 || cleanupFailures.length > 0) {+ throw new HostFleetReconcileError(hostFailures, cleanupFailures)+ }+ }++ private async listManagedHostDeployments(): Promise<k8s.V1Deployment[]> {+ const response = await this.appsApi.listNamespacedDeployment({+ namespace: config.hostNamespace,+ labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,+ })+ return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])}-}function canonicalStringify(obj: Record<string, unknown>): string {diff --cc host-context-controller/src/k8s/gfsFactory.tsindex d4d6c40da,a93a21a21..81430d656--- a/host-context-controller/src/k8s/gfsFactory.ts+++ b/host-context-controller/src/k8s/gfsFactory.ts@@@ -249,6 -256,18 +256,17 @@@ 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.readerPgSecretName+ const pgSecretKey = role === 'writer' ? config.pgSecretKey : config.readerPgSecretKey+ const copyEnvEntries: ReadonlyArray<readonly [string, string | undefined]> = [+ ['GFS_SYNC_COPY_MAX_OBJECTS', config.syncCopyMaxObjects],+ ['GFS_SYNC_COPY_MAX_BYTES', config.syncCopyMaxBytes],+ ['GFS_SYNC_COPY_TIMEOUT_MS', config.syncCopyTimeoutMs],+ ]+ const copyEnv = copyEnvEntries.flatMap(([name, value]): k8s.V1EnvVar[] =>+ value === undefined ? [] : [{ name, value }]+ )+return [{ name: 'GFS_PORT', value: String(config.gfscPort) },{ name: 'GFS_STORAGE_PATH', value: GFS_MOUNT_PATH },diff --cc host-context-controller/src/k8sClient.test.tsindex cdf5223f1,c4f573f0e..375a37333--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@@ -2313,13 -2398,11 +2398,12 @@@ describe('McpServerWatcher Host periodiconst reconcile = vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async host => {order.push(`watch:${host.name}:${host.generation}`)})- const reconcileDelete = vi- .spyOn(hostReconciler, 'reconcileDelete')- .mockImplementation(async name => {- order.push(`delete:${name}`)- })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('Periodic resync',@@@ -2327,22 -2410,77 +2411,73 @@@'full') as Promise<void>await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())- const modified = hostWatchCallback('MODIFIED', {- metadata: { name: 'updated-host', namespace: 'mcp-host', generation: 2 },- spec: { host: 'updated-host', lifecycle: { stateless: true } },- })- const deleted = hostWatchCallback('DELETED', {- metadata: { name: 'deleted-host', namespace: 'mcp-host', generation: 2 },- spec: { host: 'deleted-host' },++ // A watch event for an INDEPENDENT Host must reconcile without waiting for+ // the blocked full pass — the removed global tail no longer gates it.+ const independent = hostWatchCallback('MODIFIED', {+ metadata: { name: 'independent-host', namespace: 'mcp-host', generation: 5 },+ spec: { host: 'independent-host', lifecycle: { stateless: true } },})+ await vi.waitFor(() =>+ expect(reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'independent-host', generation: 5 }),+ 'urgent' // direct watch admission reconciles on the urgent lane (F1)+ )+ )+ // Independent Host progressed while the full pass is still blocked.+ expect(order).toContain('watch:independent-host:5')+ expect(order).not.toContain('full:end')- await Promise.resolve()- expect(reconcile).not.toHaveBeenCalled()- expect(reconcileDelete).not.toHaveBeenCalled()fullReconcile.resolve()- await Promise.all([full, modified, deleted])+ await Promise.all([full, independent])+ expect(order).toContain('full:end')+ watcher.stop()+ })- expect(order).toEqual(['full:start', 'full:end', 'watch:updated-host:2', 'delete:deleted-host'])+ it('dispatches same-Host watch events to the per-Host chain in causal order', async () => {+ vi.clearAllMocks()+ const order: string[] = []+ type HostWatchCallback = (type: string, host: unknown) => Promise<void>+ let hostWatchCallback: HostWatchCallback | undefined+ mocks.watch.mockImplementation(+ async (path: string, _query: unknown, callback: HostWatchCallback) => {+ if (path.endsWith('/hosts')) hostWatchCallback = callback+ return { abort: vi.fn() }+ }+ )+ mocks.listNamespacedCustomObject.mockImplementation(async () => ({ items: [] }))+ const watcher = new McpServerWatcher()+ const hostReconciler = watcher.getHostReconciler()+ // The reconcile()/reconcileDelete() spies stand in for the per-Host chain;+ // the actual serializeByHost non-overlap guarantee is proven in+ // hostReconciler.test.ts (delete serialization). Here we assert the+ // k8sClient dispatch order for the SAME Host is causal and the final cache+ // state belongs to the newest event (§13.1: N+1 follows the same chain).+ vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async (host: HostCRD) => {+ order.push(`reconcile:${host.name}:${host.generation}`)+ })+ vi.spyOn(hostReconciler, 'reconcileDelete').mockImplementation(async (name: string) => {+ order.push(`delete:${name}`)+ })+ await (watcher as any).startHostWatch('same-host-rv')+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ ;(watcher as any).hostCacheSynced = true++ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 1 },+ spec: { host: 'same-host', lifecycle: { stateless: false } },+ })+ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 2 },+ spec: { host: 'same-host', lifecycle: { stateless: true } },+ })+ await hostWatchCallback('DELETED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 3 },+ 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()})@@@ -2828,6 -2971,7 +2968,10 @@@ describe('McpServerWatcher Host watch gspec: { 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)@@@ -3049,6 -3214,251 +3214,257 @@@watcher.stop()})+ it('recovery diff enqueues an immediate per-Host delete for a disappeared Host (#827 item 1)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // Fresh authoritative snapshot holds only "live-host"; "gone-host" was in the+ // pre-recovery inventory (previousNames) and has genuinely disappeared.+ ;(watcher as any).enqueueRecoveredHostDeletes(+ [{ name: 'live-host', namespace: 'mcp-host', uid: 'u1', spec: { host: 'live-host' } }],+ new Set(['live-host', 'gone-host'])+ )+ await vi.waitFor(() =>+ 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()+ })++ // The recovery diff resolves absence at LIST time. Between that diff and the+ // moment the delete is admitted to the per-Host serializer, the recreation's+ // ADDED can land: the watch callback sets `this.hosts` SYNCHRONOUSLY and+ // enters the per-Host chain FIRST, while the fire-and-forget dispatch queues+ // the delete SECOND. serializeByHost is strict FIFO, so without a fence the+ // new bundle is created and then wiped. The fence must therefore read the+ // LIVE cache at admission, not a value captured at enqueue time.+ //+ // This is the case the sibling recreation test does NOT cover: there the+ // recreated Host is present in the snapshot, so enqueueRecoveredHostDeletes+ // short-circuits on snapshotNames.has(name) and never dispatches at all.+ it('recovery delete carries a live-cache fence for a Host recreated during admission (#827 F2 parity)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // "ghost" is absent from the fresh authoritative snapshot → genuinely+ // disappeared → dispatched for delete.+ ;(watcher as any).enqueueRecoveredHostDeletes([], new Set(['ghost']))+ await vi.waitFor(() => expect(reconcileDelete).toHaveBeenCalled())++ const [, , opts] = reconcileDelete.mock.calls[0] as [+ string,+ string,+ { skipIf?: () => boolean } | undefined,+ ]+ expect(opts?.skipIf, 'the recovery delete must carry a skipIf fence').toBeTypeOf('function')++ // Cache does not hold the name → the Host really is gone → do NOT skip.+ expect(opts!.skipIf!()).toBe(false)++ // The recreation lands in the live cache during the admission window.+ ;(watcher as any).hosts.set('ghost', {+ name: 'ghost',+ namespace: 'mcp-host',+ uid: 'uid-recreated',+ generation: 1,+ spec: { host: 'ghost' },+ })+ // Same fence, re-evaluated at admission → skip the destructive delete.+ expect(opts!.skipIf!()).toBe(true)+ watcher.stop()+ })++ it('recovery diff reconciles (does NOT delete) a same-name Host recreated with a new uid (#827 items 1+2)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // The recreated Host is the CURRENT cache entry the urgent dispatch resolves.+ ;(watcher as any).hosts.set('x', {+ name: 'x',+ namespace: 'mcp-host',+ uid: 'uid-B',+ generation: 1,+ spec: { host: 'x' },+ })+ // Same name, same generation (reset to 1), but a DIFFERENT uid than before.+ ;(watcher as any).enqueueRecoveredUrgentHosts(+ [{ name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 1, spec: { host: 'x' } }],+ new Set(['x']),+ new Map([['x', 1]]),+ new Map([['x', 'uid-A']])+ )+ // The snapshot still contains "x" by name, so the recovery-delete diff never+ // treats it as a disappearance.+ ;(watcher as any).enqueueRecoveredHostDeletes(+ [{ name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 1, spec: { host: 'x' } }],+ new Set(['x'])+ )+ await vi.waitFor(() =>+ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'x' }), 'urgent')+ )+ expect(reconcileDelete).not.toHaveBeenCalled()+ watcher.stop()+ })++ 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(+ (watcher as any).isCurrentHostWatchEvent(+ 'MODIFIED',+ { name: 'x', namespace: 'mcp-host', uid: 'uid-A', generation: 3 },+ 7+ )+ ).toBe(false)+ // The current identity is admitted.+ expect(+ (watcher as any).isCurrentHostWatchEvent(+ 'MODIFIED',+ { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 },+ 7+ )+ ).toBe(true)+ watcher.stop()+ })++ it('recovery urgently admits a wake-pending Host that is otherwise unchanged (§10.2 step 7 wake branch)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ // A Host unchanged by name, generation AND uid but carrying a pending wake+ // annotation must still be admitted on the urgent lane after recovery, so a+ // wake discovered during the LIST→WATCH gap is not deferred to the slow+ // background fleet pass (A3: 2m47s admission vs 3s execution). This closes+ // the recovery-time wake branch that the watch-time admission test does not+ // exercise: deleting `|| wakePending` from enqueueRecoveredUrgentHosts()+ // would make this assertion fail.+ ;(watcher as any).hosts.set('waker', {+ name: 'waker',+ namespace: 'mcp-host',+ uid: 'u1',+ generation: 4,+ annotations: { 'clerum.io/wake-requested': '7' },+ spec: { host: 'waker' },+ })+ ;(watcher as any).enqueueRecoveredUrgentHosts(+ [+ {+ name: 'waker',+ namespace: 'mcp-host',+ uid: 'u1',+ generation: 4,+ annotations: { 'clerum.io/wake-requested': '7' },+ spec: { host: 'waker' },+ },+ ],+ new Set(['waker']), // NOT new+ new Map([['waker', 4]]), // NOT changed (same 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()+ })++ it('recovery does NOT urgently dispatch a fully-unchanged Host with no wake annotation', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ // Same name, generation and uid as before recovery and no wake pending: the+ // background fleet pass already covers it, so recovery must NOT enqueue a+ // redundant urgent reconcile (guards the negative side of the predicate).+ ;(watcher as any).hosts.set('steady', {+ name: 'steady',+ namespace: 'mcp-host',+ uid: 'u1',+ generation: 4,+ 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']])+ )+ // Let any erroneously-scheduled async dispatch run before asserting absence.+ await Promise.resolve()+ await Promise.resolve()+ expect(reconcile).not.toHaveBeenCalled()+ watcher.stop()+ })++ it('reconciles a retried Host watch event on the "retry" lane, not "urgent" (F1)', async () => {+ vi.useFakeTimers()+ let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefined+ mocks.watch.mockImplementation(+ async (+ _path: string,+ _params: object,+ callback: (type: string, apiObj: any) => Promise<void>+ ) => {+ hostWatchCallback = callback+ return { abort: vi.fn() }+ }+ )+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockRejectedValueOnce(new Error('transient'))+ .mockResolvedValue(undefined)+ await (watcher as any).startHostWatch('test-host-rv')+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')++ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'retry-lane-host', namespace: 'mcp-host', generation: 2 },+ spec: { host: 'retry-lane-host', lifecycle: { stateless: true } },+ })+ // First attempt is the direct/urgent admission.+ expect(reconcile).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ name: 'retry-lane-host' }),+ 'urgent'+ )+ await vi.advanceTimersByTimeAsync(5000)+ // The retry attempt populates the distinct "retry" lane.+ expect(reconcile).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ name: 'retry-lane-host' }),+ 'retry'+ )+ watcher.stop()+ vi.useRealTimers()+ })+it('automatically retries a transient Host watch reconciliation failure', async () => {vi.useFakeTimers()let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefineddiff --cc host-context-controller/src/k8sClient.tsindex c452d9c4c,e850c29ae..ea754b7b5--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@@ -17,7 -17,17 +17,12 @@@ import { config } from './configimport { gfsDefaultFactoryConfig } from './gfsConfig'import { GfsReconciler } from './gfsReconciler'import { ControlApiGfsSeedClient } from './gfsSeedClient'- import { HostFleetReconcileError, HostReconciler, type ResolvedSfsMount } from './hostReconciler'+ import {+ HostFleetReconcileError,- HostReconciler,+ type HostReconcileSource,++ HostReconciler,+ type ResolvedSfsMount,+ } from './hostReconciler'-import {- hostDeleteCleanupTotal,- hostFleetRequestsTotal,- hostWatchRecoverySeconds,-} from './metrics'import {type InfrastructureTelemetryReporter,createInfrastructureTelemetryReporter,@@@ -25,6 -35,6 +30,7 @@@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 --cc host-context-controller/src/metrics.tsindex 5dd7c2549,4de90228e..75b8cc5f0--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@@ -42,6 -42,33 +42,31 @@@ function gauge(options:})}+ /**+ * Buckets spanning sub-second admission through the urgent (5s), watch-recovery+ * (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: {+ name: string+ help: string+ labelNames?: readonly string[]+ buckets?: readonly number[]+ }): Histogram<string> {+ const existing = registry.getSingleMetric(options.name)+ if (existing) return existing as Histogram<string>+ return new Histogram({+ name: options.name,+ help: options.help,+ labelNames: [...(options.labelNames ?? [])],+ buckets: [...(options.buckets ?? RECONCILE_LATENCY_BUCKETS)],+ registers: [registry],+ })+ }+export const mcpServersTotal = gauge({name: 'clerum_hcc_mcpservers_total',help: 'Total number of McpServer CRDs tracked by HCC',diff --cc host-context-controller/test/hostReconciler.heartbeat.test.tsindex 3c5ce8ece,6d9918a16..4e6593024--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@@ -439,7 -439,7 +439,8 @@@ describe('HostReconciler.publishSuspendlifecycle: {state: 'active',wakeHandledGeneration: 0,- reason: '1 CommunicationChannel(s) reference this Host',- 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',},},})@@@ -452,7 -452,7 +453,8 @@@freshHostRead({state: 'active',wakeHandledGeneration: 0,- reason: '1 CommunicationChannel(s) reference this Host',- 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 --cc host-context-controller/test/hostReconciler.lifecycle.test.tsindex b665f6268,3bd808b44..d624bf4e2--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts@@@ -793,7 -793,7 +793,8 @@@ describe('HostReconciler stateless lifeexpect(writes[1].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 5,- reason: '1 CommunicationChannel(s) reference this Host',- 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',@@@ -872,7 -872,7 +873,8 @@@expect(writes[1].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 6,- reason: '1 CommunicationChannel(s) reference this Host',- 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',})})@@@ -988,7 -988,7 +990,9 @@@)const writes = lifecycleStatusWrites(customApi)expect(writes).toHaveLength(2)- expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host')- 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 () => {@@@ -1321,7 -1388,7 +1392,8 @@@ describe('HostReconciler stateless lifeexpect(writes[0].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 3,- reason: '1 CommunicationChannel(s) reference this Host',- 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')})@@@ -1535,7 -1602,7 +1607,8 @@@ describe('HostReconciler stateless lifeexpect(writes.at(-1)?.lifecycle).toEqual({state: 'active',wakeHandledGeneration: 3,- reason: '1 CommunicationChannel(s) reference this Host',- 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',})})@@@ -1563,7 -1630,7 +1636,8 @@@expect(writes.at(-1)?.lifecycle).toEqual({state: 'active',wakeHandledGeneration: 2,- reason: '1 CommunicationChannel(s) reference this Host',- 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',})})@@@ -1589,7 -1656,7 +1663,8 @@@expect(writes.at(-1)?.lifecycle).toEqual({state: 'suspended',wakeHandledGeneration: 5,- reason: '1 CommunicationChannel(s) reference this Host',- 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 --cc host-context-controller/test/hostReconciler.test.tsindex bec0d1a74,d250cf53e..ccb55d3a8--- a/host-context-controller/test/hostReconciler.test.ts+++ b/host-context-controller/test/hostReconciler.test.ts@@@ -1,6 -1,6 +1,7 @@@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,diff --cc host-context-controller/test/statelessDeployment.workspaceLayout.test.tsindex 000000000,790d3833b..7b75c2327mode 000000,100644..100644--- a/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts+++ b/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts@@@ -1,0 -1,331 +1,330 @@@+ import { afterEach, describe, expect, it } from 'vitest'+ import { execFileSync, spawnSync } from 'node:child_process'+ import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ symlinkSync,+ writeFileSync,+ } from 'node:fs'+ import { tmpdir } from 'node:os'+ import { join } from 'node:path'+ import { buildWorkspaceLayoutInitScript } from '../src/statelessDeployment'++ const roots: string[] = []++ function makeRoot(): string {+ const root = mkdtempSync(join(tmpdir(), 'clerum-workspace-layout-'))+ roots.push(root)+ return root+ }++ function runMigration(root: string): void {+ execFileSync('/bin/sh', ['-c', buildWorkspaceLayoutInitScript(root)], { stdio: 'pipe' })+ }++ function migrationFailure(root: string): { stderr?: Buffer } {+ try {+ runMigration(root)+ } catch (error) {+ return error as { stderr?: Buffer }+ }+ throw new Error('expected workspace layout migration to fail')+ }++ // Captures stderr even on SUCCESS (execFileSync only surfaces stderr on throw),+ // so the loud round-trip resolution log can be asserted on a passing migration.+ function runMigrationCapture(root: string): { status: number; stderr: string } {+ const res = spawnSync('/bin/sh', ['-c', buildWorkspaceLayoutInitScript(root)], {+ encoding: 'utf8',+ })+ if (res.error) throw res.error+ return { status: res.status ?? -1, stderr: res.stderr ?? '' }+ }++ function stateBackups(root: string, prefix = 'state.db'): string[] {+ return readdirSync(join(root, 'state'))+ .filter(name => name.startsWith(`${prefix}.pre-`) && name.endsWith('.bak'))+ .sort()+ }++ afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+ })++ describe('stateless workspace layout migration', () => {+ it('moves legacy workspace and SQLite files once and is idempotent', () => {+ const root = makeRoot()+ writeFileSync(join(root, 'notes.md'), 'workspace-data')+ writeFileSync(join(root, 'state.db'), 'durable-db')++ runMigration(root)+ runMigration(root)++ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('workspace-data')+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')- }, // 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++ }, // 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+ // turn a completed idempotency check into a harness timeout.+ 15_000)++ it('finishes a partial migration whose SQLite source is already under workspace', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ writeFileSync(join(root, 'workspace', 'state.db'), 'durable-db')++ runMigration(root)++ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')+ })++ it.each([+ {+ rootArtifact: 'state.db',+ workspaceArtifact: 'state.db-wal',+ },+ {+ rootArtifact: 'state.db-shm',+ workspaceArtifact: 'state.db',+ },+ ])(+ 'fails closed when $rootArtifact and $workspaceArtifact split SQLite source authority',+ ({ rootArtifact, workspaceArtifact }) => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ writeFileSync(join(root, 'notes.md'), 'must-stay-root')+ writeFileSync(join(root, rootArtifact), 'root-artifact')+ writeFileSync(join(root, 'workspace', workspaceArtifact), 'workspace-artifact')++ expect(String(migrationFailure(root).stderr)).toContain(+ 'SQLite artifacts are split across root and workspace'+ )+ expect(readFileSync(join(root, 'notes.md'), 'utf8')).toBe('must-stay-root')+ expect(readFileSync(join(root, rootArtifact), 'utf8')).toBe('root-artifact')+ expect(readFileSync(join(root, 'workspace', workspaceArtifact), 'utf8')).toBe(+ 'workspace-artifact'+ )+ }+ )++ it('fails closed without overwriting a duplicate workspace entry', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ writeFileSync(join(root, 'notes.md'), 'legacy-data')+ writeFileSync(join(root, 'workspace', 'notes.md'), 'current-data')++ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')+ expect(readFileSync(join(root, 'notes.md'), 'utf8')).toBe('legacy-data')+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('current-data')+ })++ it('fails closed without overwriting an existing durable SQLite file', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'workspace', 'state.db'), 'legacy-db')+ writeFileSync(join(root, 'state', 'state.db'), 'current-db')++ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')+ expect(readFileSync(join(root, 'workspace', 'state.db'), 'utf8')).toBe('legacy-db')+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('current-db')+ })++ it('resolves a root SQLite round-trip collision: backs up the older destination and migrates the fresher root source', () => {+ // Addendum 6 item 6 (newest-source-wins): a stateful<->stateless round-trip+ // leaves BOTH root state.db (freshest — the stateful life just left) and an+ // earlier stateless life's state/state.db. The migration must self-heal, not+ // deadlock: back up the older destination (never delete) and migrate the+ // fresher root source in, while non-SQLite root content still moves to+ // workspace/.+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'notes.md'), 'must-migrate-to-workspace')+ writeFileSync(join(root, 'state.db'), 'fresh-stateful-db')+ writeFileSync(join(root, 'state', 'state.db'), 'older-stateless-db')++ const { status, stderr } = runMigrationCapture(root)++ expect(status).toBe(0)+ // Fresher root data migrated into the durable destination.+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('fresh-stateful-db')+ expect(existsSync(join(root, 'state.db'))).toBe(false)+ // Non-SQLite root content still migrated to workspace/.+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe(+ 'must-migrate-to-workspace'+ )+ // Older destination preserved (never deleted) as a timestamped backup.+ const backups = stateBackups(root)+ expect(backups).toHaveLength(1)+ expect(readFileSync(join(root, 'state', backups[0]), 'utf8')).toBe('older-stateless-db')+ // Loud one-line resolution log naming the backup + migration.+ expect(stderr).toContain('newest-source-wins round-trip resolution')+ expect(stderr).toContain('.pre-')+ })++ it('renames wal/shm destination companions in lockstep with the state.db backup', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'state'))+ for (const db of ['state.db', 'state.db-wal', 'state.db-shm']) {+ writeFileSync(join(root, db), `fresh-${db}`)+ writeFileSync(join(root, 'state', db), `older-${db}`)+ }++ const { status } = runMigrationCapture(root)+ expect(status).toBe(0)++ // All three fresher root companions migrated into state/.+ for (const db of ['state.db', 'state.db-wal', 'state.db-shm']) {+ expect(readFileSync(join(root, 'state', db), 'utf8')).toBe(`fresh-${db}`)+ expect(existsSync(join(root, db))).toBe(false)+ }+ // All three older destinations backed up under ONE shared timestamp suffix.+ const backups = readdirSync(join(root, 'state'))+ .filter(name => name.endsWith('.bak'))+ .sort()+ expect(backups).toHaveLength(3)+ const suffixes = new Set(+ backups.map(name => name.replace(/^state\.db(-wal|-shm)?\.pre-/, '').replace(/\.bak$/, ''))+ )+ expect(suffixes.size).toBe(1)+ expect(+ readFileSync(join(root, 'state', backups.find(f => f.startsWith('state.db.pre-'))!), 'utf8')+ ).toBe('older-state.db')+ expect(+ readFileSync(+ join(root, 'state', backups.find(f => f.startsWith('state.db-wal.pre-'))!),+ 'utf8'+ )+ ).toBe('older-state.db-wal')+ expect(+ readFileSync(+ join(root, 'state', backups.find(f => f.startsWith('state.db-shm.pre-'))!),+ 'utf8'+ )+ ).toBe('older-state.db-shm')+ })++ it('is idempotent after a backup: a second run with no root source is a no-op', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'state.db'), 'fresh-db')+ writeFileSync(join(root, 'state', 'state.db'), 'older-db')++ const first = runMigrationCapture(root)+ expect(first.status).toBe(0)+ const afterFirst = stateBackups(root)+ expect(afterFirst).toHaveLength(1)++ const second = runMigrationCapture(root)+ expect(second.status).toBe(0)+ // No new backup, destination unchanged, no resolution log on the no-op run.+ expect(stateBackups(root)).toEqual(afterFirst)+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('fresh-db')+ expect(second.stderr).not.toContain('newest-source-wins')+ })++ it('backs up under a NEW unique suffix on each later round-trip collision', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'state.db'), 'stateful-life-1')+ writeFileSync(join(root, 'state', 'state.db'), 'stateless-life-0')++ expect(runMigrationCapture(root).status).toBe(0)+ // A new stateful life re-creates the root source for a second round-trip.+ writeFileSync(join(root, 'state.db'), 'stateful-life-2')+ expect(runMigrationCapture(root).status).toBe(0)++ // Two distinct backups: nothing was overwritten across the two collisions.+ const backups = stateBackups(root)+ expect(backups).toHaveLength(2)+ const contents = backups.map(name => readFileSync(join(root, 'state', name), 'utf8')).sort()+ expect(contents).toEqual(['stateful-life-1', 'stateless-life-0'].sort())+ // Final durable state is the newest life.+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('stateful-life-2')+ })++ it('keeps a WORKSPACE SQLite source colliding with the destination fail-loud (genuinely ambiguous)', () => {+ // Only the ROOT round-trip collision self-heals. A workspace SQLite source+ // (an interrupted partial migration) colliding with an existing durable+ // destination stays fail-loud, preserving every source for recovery.+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'workspace', 'state.db'), 'legacy-db')+ writeFileSync(join(root, 'state', 'state.db'), 'current-db')++ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')+ expect(readFileSync(join(root, 'workspace', 'state.db'), 'utf8')).toBe('legacy-db')+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('current-db')+ expect(stateBackups(root)).toHaveLength(0)+ })++ it.each(['workspace', 'state'])(+ 'rejects a symlinked %s directory without writing through it',+ managedDir => {+ const root = makeRoot()+ const outside = makeRoot()+ symlinkSync(outside, join(root, managedDir), 'dir')+ writeFileSync(join(root, managedDir === 'workspace' ? 'notes.md' : 'state.db'), 'must-stay')++ expect(String(migrationFailure(root).stderr)).toContain(+ `${managedDir} directory is a symlink`+ )+ expect(+ readFileSync(join(root, managedDir === 'workspace' ? 'notes.md' : 'state.db'), 'utf8')+ ).toBe('must-stay')+ expect(existsSync(join(outside, 'notes.md'))).toBe(false)+ expect(existsSync(join(outside, 'state.db'))).toBe(false)+ }+ )++ it('rejects a symlinked PVC root without touching its target', () => {+ const target = makeRoot()+ const parent = makeRoot()+ const linkedRoot = join(parent, 'workspace-root')+ writeFileSync(join(target, 'notes.md'), 'target-data')+ symlinkSync(target, linkedRoot, 'dir')++ expect(String(migrationFailure(linkedRoot).stderr)).toContain('PVC root is a symlink')+ expect(readFileSync(join(target, 'notes.md'), 'utf8')).toBe('target-data')+ expect(existsSync(join(target, 'workspace'))).toBe(false)+ expect(existsSync(join(target, 'state'))).toBe(false)+ })++ it('rejects a symlinked legacy source without moving it or touching its target', () => {+ const root = makeRoot()+ const outside = makeRoot()+ const outsideTarget = join(outside, 'target.txt')+ const source = join(root, 'notes.md')+ writeFileSync(outsideTarget, 'outside-data')+ symlinkSync(outsideTarget, source)++ expect(String(migrationFailure(root).stderr)).toContain('legacy source is a symlink')+ expect(lstatSync(source).isSymbolicLink()).toBe(true)+ expect(readFileSync(outsideTarget, 'utf8')).toBe('outside-data')+ expect(existsSync(join(root, 'workspace', 'notes.md'))).toBe(false)+ })++ it.each(['workspace', 'state'])(+ 'rejects a symlinked SQLite artifact under %s without touching its target',+ sqliteDir => {+ const root = makeRoot()+ const outside = makeRoot()+ const outsideTarget = join(outside, 'outside-state.db')+ mkdirSync(join(root, sqliteDir))+ writeFileSync(outsideTarget, 'outside-db')+ symlinkSync(outsideTarget, join(root, sqliteDir, 'state.db'))+ if (sqliteDir === 'state') writeFileSync(join(root, 'state.db'), 'legacy-db')++ expect(String(migrationFailure(root).stderr)).toContain('SQLite')+ expect(readFileSync(outsideTarget, 'utf8')).toBe('outside-db')+ expect(lstatSync(join(root, sqliteDir, 'state.db')).isSymbolicLink()).toBe(true)+ if (sqliteDir === 'state')+ expect(readFileSync(join(root, 'state.db'), 'utf8')).toBe('legacy-db')+ }+ )+ })diff --cc mcp-host/src/internalTools/gfs.test.tsindex ae59db460,ab15d5eff..ed2b8d154--- a/mcp-host/src/internalTools/gfs.test.ts+++ b/mcp-host/src/internalTools/gfs.test.ts@@@ -123,4 -156,114 +156,121 @@@ describe('buildGfsWriteTools (P4)', ()expect(r.error).toMatch(/If-Match/i)expect(c.write).not.toHaveBeenCalled()})++ 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' },+ ],+ ])('rejects invalid If-Match values before %s reaches gfsc', async (name, baseArgs) => {+ for (const ifMatch of [Number.NaN, -1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {+ const c = writeClient()+ const tools = new Map(+ [...buildGfsWriteTools(c), ...buildGfsCopyTools(c)].map(tool => [tool.name, tool])+ )+ const result = await tools.get(name)!.execute({ ...baseArgs, ifMatch }, '')+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/non-negative safe-integer If-Match/)+ expect(c.write).not.toHaveBeenCalled()+ expect(c.rename).not.toHaveBeenCalled()+ expect(c.copy).not.toHaveBeenCalled()+ }+ })++ 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)+ })++ it('copies through one server-side call with the exact root contract', async () => {+ const c = writeClient()+ const tool = buildGfsCopyTools(c)[0]!+ 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)+ expect(c.copy).toHaveBeenCalledTimes(1)+ expect(c.copy).toHaveBeenCalledWith(args)+ expect(c.read).not.toHaveBeenCalled()+ expect(c.write).not.toHaveBeenCalled()+ })++ 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 },+ ''+ )+ expect(result).toEqual({ success: false, error: 'GFS mutation failed' })+ })++ it.each([+ [403, 'forbidden'],+ [409, 'conflict'],+ [412, 'precondition_failed'],+ [413, 'limit_exceeded'],+ [503, 'unavailable'],+ ])('preserves safe gfsc status/category for mutation failure %s', async (status, category) => {+ const c = writeClient({+ copy: vi.fn(async () => {+ throw new Error(+ `gfsc ${status}: private path=/data/gfs/.generations/secret sql=do-not-expose`+ )+ }),+ })+ const result = await buildGfsCopyTools(c)[0]!.execute(+ { drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination', ifMatch: 7 },+ ''+ )+ expect(result).toEqual({+ success: false,+ error: `GFS mutation failed (gfsc ${status}: ${category})`,+ })+ expect(result.error).not.toContain('/data/')+ expect(result.error).not.toContain('sql=')+ })})diff --cc mcp-host/src/internalTools/gfsClient.test.tsindex f384431ec,dbb3e561c..a575f6355--- a/mcp-host/src/internalTools/gfsClient.test.ts+++ b/mcp-host/src/internalTools/gfsClient.test.ts@@@ -28,6 -39,16 +39,17 @@@ describe('gfs runtime gfsc client', ()).toBe(false)})+ 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()+ expect(getGfsToolScopes({ get: () => encodedClaims('gfs.read') })).toBeNull()+ expect(getGfsToolScopes({ get: () => 'malformed' })).toBeNull()+ })+it('calls gfsc accessible with runtime bearer auth', async () => {const fetchFn = vi.fn(async (_input: string, _init?: RequestInit) =>jsonResponse({ ok: true, data: { items: [] } })@@@ -63,6 -84,47 +85,56 @@@})})+ it('uses exact writer routes and bodies for create, rename, and copy', async () => {+ const fetchFn = vi.fn(async (_input: string, _init?: RequestInit) =>+ jsonResponse({ ok: true, data: {} })+ )+ const client = createGfscClient({+ get: key => (key === 'MCP_HOST_GFS_TOKEN' ? 'gfs-access' : undefined),+ 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 }),- ],- [- 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/copy',- 'POST', JSON.stringify(copy),++ 'PATCH',++ JSON.stringify({ drive: 'main', newName: 'renamed.txt', ifMatch: 4 }),+ ],++ ['http://gfsc-writer.gfs.svc.cluster.local:8087/v1/copy', 'POST', JSON.stringify(copy)],+ ])+ })+it('fails loud when the mounted runtime token file is empty', async () => {const client = createGfscClient({get: () => undefined,diff --cc mcp-host/src/internalTools/gfsClient.tsindex c1bf606f8,f51305c40..115cc542f--- a/mcp-host/src/internalTools/gfsClient.ts+++ b/mcp-host/src/internalTools/gfsClient.ts@@@ -1,6 -1,7 +1,7 @@@- import { existsSync } from 'node:fs'+ import { existsSync, readFileSync } from 'node:fs'import { readFile } from 'node:fs/promises'-import type { GfscWriteClient } from './gfs'+ import { decodeRuntimeJwtScopes } from '../workflow/mcpHostRuntimeJwt'+import type { GfscWriteClient } from './gfs'const DIRECT_KEY = 'MCP_HOST_GFS_TOKEN'const FILE_KEY = 'MCP_HOST_GFS_TOKEN_FILE'diff --cc mcp-host/src/workflow/mcpHostRuntimeJwt.tsindex 265ac194e,65d9c84c9..e9b8902e6--- a/mcp-host/src/workflow/mcpHostRuntimeJwt.ts+++ b/mcp-host/src/workflow/mcpHostRuntimeJwt.ts@@@ -13,6 -13,24 +13,27 @@@ type RuntimeJwtClaims =recipeName?: unknownexp?: unknowniat?: unknown+ scopes?: unknown+ }++ /**+ * Decode a runtime token's scope advertisement without treating it as an+ * authorization decision. Callers use this only to hide tools the token can+ * never invoke; the receiving service must still verify and authorize it.+ */+ 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.scopes+ } catch {+ return null+ }}export type DecodedRuntimeJwtClaims = {diff --cc rpc-proxy/src/__tests__/wake-route-coverage.test.tsindex 000000000,eed0e33ba..b7289c749mode 000000,100644..100644--- a/rpc-proxy/src/__tests__/wake-route-coverage.test.ts+++ b/rpc-proxy/src/__tests__/wake-route-coverage.test.ts@@@ -1,0 -1,554 +1,559 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+ import type { Response as ExpressResponse } from 'express'+ import express from 'express'+ import request from 'supertest'+ import {+ createRpcRouter,+ respondControlApiHostAccessRejection,+ respondUpstreamUnavailable,+ } from '../routes/rpc.js'++ // ── Issue #791 §11.4/§11.5 — extend wake-and-hold to the remaining finite+ // Desktop routes, and prove terminal-response (duplicate-write) safety in the+ // route-level outer catches. Wake capability rides on the token; the route+ // scope guards are UNCHANGED.++ const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))+ const serviceMock = vi.hoisted(() => ({+ listAllowedServersForUser: vi.fn(),+ resolveServerConnectionForUser: vi.fn(),+ resolveHostConnectionForUser: vi.fn(),+ validateRpcRequest: vi.fn(),+ forwardRpcToServer: vi.fn(),+ forwardHostMessageToHost: vi.fn(),+ forwardHostActivity: vi.fn(),+ forwardHostStatus: vi.fn(),+ forwardHostHealth: vi.fn(),+ forwardTaskResultFromHost: vi.fn(),+ forwardCancelToHost: vi.fn(),+ UpstreamHostError: class UpstreamHostError extends Error {+ constructor(+ public readonly status: number,+ public readonly bodySnippet: string+ ) {+ super(`Upstream host returned ${status}: ${bodySnippet}`)+ this.name = 'UpstreamHostError'+ }+ },+ }))+ const controlApiMock = vi.hoisted(() => ({+ fetchUserAllowedServersFromControlApi: vi.fn(),+ fetchHostConnectionFromControlApi: vi.fn(),+ requestHostWakeFromControlApi: vi.fn(),+ }))++ vi.mock('../authToken.js', () => authTokenMock)+ vi.mock('../services/mcpProxyService.js', () => serviceMock)+ vi.mock('../services/controlApiRestService.js', () => controlApiMock)++ const HOST_CONNECTION = {+ name: 'chatllm',+ url: 'http://chatllm.mcp-host.svc.cluster.local:8080',+ headers: { 'x-clerum-edge-caller': 'rpc-proxy' },+ }++ function claims(scopes: string[]) {+ return {+ sub: 'user-uuid-123',+ typ: 'user' as const,+ accessScope: 'team' as const,+ teamId: 'team-1',+ scopes,+ hostRefs: ['chatllm'],+ jti: 'j1',+ iat: 1,+ exp: 9999999999,+ }+ }++ function makeApp() {+ const app = express()+ app.use(express.json())+ app.use(createRpcRouter())+ app.use(+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : 'Internal error' })+ }+ )+ 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,+ headers: new Headers(headers),+ text: () => Promise.resolve(body),+ arrayBuffer: () => Promise.resolve(Buffer.from(body).buffer as ArrayBuffer),+ } as unknown as Response+ }++ function hostDownError(): Error {+ return new TypeError('fetch failed')+ }++ function drainingResponse(): Response {+ return mockFetchResponse(503, JSON.stringify({ code: 'host_draining', retryAfterMs: 1000 }), {+ 'content-type': 'application/json',+ })+ }++ const originalFetch = globalThis.fetch++ beforeEach(() => {+ vi.clearAllMocks()+ serviceMock.resolveHostConnectionForUser.mockResolvedValue({ ...HOST_CONNECTION })- controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({ kind: 'active', wakeGeneration: null })++ controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({++ kind: 'active',++ wakeGeneration: null,++ })+ })++ afterEach(() => {+ globalThis.fetch = originalFetch+ })++ describe('§11.4 wake coverage — GET /rpc/hosts/:hostRef/models', () => {+ it('a wake-capable token wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .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++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/models')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ models: [] })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('a NON-wake token gets the deterministic legacy result and triggers NO wake', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ const fetchMock = vi.fn().mockRejectedValue(hostDownError())+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/models')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ describe('§11.4 wake coverage — POST /rpc/hosts/:hostRef/model', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:model:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ effective: 'next-task' })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/model')+ .set('authorization', 'Bearer tok')+ .send({ chatId: 'c1', model: 'claude-haiku-4-5' })+ .expect(200)++ expect(res.body).toEqual({ effective: 'next-task' })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ describe('§11.4 wake coverage — context-breakdown honors the draining fence', () => {+ it('a 503 host_draining triggers a wake and re-forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(drainingResponse())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ breakdown: {} }), {+ 'content-type': 'application/json',+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ breakdown: {} })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })++ 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 fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/missing/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(404)++ expect(res.body).toEqual({ error: 'session not found' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ describe('§11.4 wake coverage — approvals approve', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ ok: true })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/approve')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(200)++ // The approve route relays the upstream body verbatim as a raw string+ // (no JSON content-type is set), so read it via res.text.+ expect(JSON.parse(res.text)).toEqual({ ok: true })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ describe('§11.4 wake coverage — artifacts list and download', () => {+ it('artifacts list wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify([{ filename: 'a.pdf' }])))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(JSON.parse(res.text)).toEqual([{ filename: 'a.pdf' }])+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })++ it('artifact download wakes on host-down and streams after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, 'PDF-BYTES', { 'content-type': 'application/pdf' })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts/report.pdf/download')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.headers['content-type']).toContain('application/pdf')+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ // ── §13.4 row 1 — GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages ──+ // sessions-passthrough.test.ts already proves the "wake accepted, host still+ // down → host_waking" variant for this transcript route; the "retry after+ // readiness → operation result" cell (§13.4 row 1 proper) is proven here.+ describe('§13.4 row 1 — session transcript wakes on host-down and re-forwards after active', () => {+ it('a wake-capable token wakes then re-forwards the transcript after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ agent: 'chatllm', chatId: 'c1', turns: [] }), {+ 'content-type': 'application/json',+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ agent: 'chatllm', chatId: 'c1', turns: [] })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })+ })++ // ── §11.4 wake coverage — approvals/deny (row 1) ────────────────────────────+ // Closes the audit gap: POST approvals/deny had no route-level wake test at+ // all. Mirrors the approve row-1 test above; the route stays host:approval:write+ // and relays the upstream body verbatim as a raw string.+ describe('§11.4 wake coverage — approvals deny', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ ok: true })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/deny')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(200)++ expect(JSON.parse(res.text)).toEqual({ ok: true })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ // ── §13.4 row 3 — GET /rpc/hosts/:hostRef/tasks/:taskId/result ──────────────+ // The other finite routes assert their plain-forward path in their own suites+ // (model-selection, approval-artifacts, sessions-passthrough). The task-result+ // route only had the wake path, so its active/ready row is proven here: even a+ // 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',+ })++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/tasks/t-7/result')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ status: 'completed', response: 'done' })+ expect(serviceMock.forwardTaskResultFromHost).toHaveBeenCalledTimes(1)+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ // ── §13.4 row 2 — suspended host + NON-wake token ───────────────────────────+ // A finite operation whose token lacks host:wake:write must return today's+ // deterministic legacy availability result (502 Upstream host unavailable) and+ // NEVER consult the wake plane — no fallback grant is minted (§11.2, §13.4).+ // GET /models already asserts this cell above; the remaining finite routes are+ // proven here so every wake-eligible route has an explicit non-wake row.+ describe('§13.4 row 2 — NON-wake token gets the deterministic legacy result and triggers NO wake', () => {+ it('POST messages', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardHostMessageToHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/messages')+ .set('authorization', 'Bearer tok')+ .send({ content: 'hello' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST approvals/approve', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/approve')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST approvals/deny', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/deny')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions/:agent/:chatId/messages (transcript)', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions/:agent/:chatId/context-breakdown', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST model', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:model:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/model')+ .set('authorization', 'Bearer tok')+ .send({ chatId: 'c1', model: 'claude-haiku-4-5' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET tasks/:taskId/result', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardTaskResultFromHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/tasks/t-1/result')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST tasks/:taskId/cancel', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardCancelToHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/tasks/t-1/cancel')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET artifacts', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET artifacts/:filename/download', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts/report.pdf/download')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ // ── §11.5 terminal-response (duplicate-write) safety ────────────────────────+ describe('§11.5 route outer-catch responders guard headersSent (one-shot settlement)', () => {+ type FakeRes = {+ headersSent: boolean+ statusCode: number+ body: unknown+ status: (code: number) => FakeRes+ json: (payload: unknown) => FakeRes+ }+ function makeRes(headersSent = false): FakeRes {+ const res: FakeRes = {+ headersSent,+ statusCode: 0,+ body: undefined,+ status(code: number) {+ res.statusCode = code+ return res+ },+ json(payload: unknown) {+ if (res.headersSent) throw new Error('Cannot set headers after they are sent to the client')+ res.headersSent = true+ res.body = payload+ return res+ },+ }+ return res+ }++ it('respondUpstreamUnavailable is a no-op once the response is committed', () => {+ const res = makeRes(true)+ expect(() =>+ respondUpstreamUnavailable(res as unknown as ExpressResponse, new Error('boom'))+ ).not.toThrow()+ expect(res.statusCode).toBe(0)+ })++ it('respondUpstreamUnavailable still writes 502 when the response is uncommitted', () => {+ const res = makeRes(false)+ respondUpstreamUnavailable(res as unknown as ExpressResponse, new Error('boom'))+ expect(res.statusCode).toBe(502)+ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ })++ it('respondControlApiHostAccessRejection is a no-op once the response is committed', () => {+ const res = makeRes(true)+ expect(() =>+ respondControlApiHostAccessRejection(res as unknown as ExpressResponse, 403)+ ).not.toThrow()+ expect(res.statusCode).toBe(0)+ })+ })diff --cc rpc-proxy/src/routes/rpc.tsindex 90e8f1194,e06ad0f9a..5722441db--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@@ -1,5 -1,5 +1,5 @@@import { Router } from 'express'- import type { Response as ExpressResponse } from 'express'-import type { NextFunction, Response as ExpressResponse } from 'express'++import type { Response as ExpressResponse, NextFunction } from 'express'import { randomUUID } from 'crypto'import { config } from '../config.js'import {diff --cc rpc-proxy/src/services/__tests__/probeHostHealth.test.tsindex 000000000,07b34521b..7efd0f186mode 000000,100644..100644--- a/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts+++ b/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts@@@ -1,0 -1,74 +1,73 @@@+ 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+ // background init and is the same signal the Pod readiness probe uses — not+ // /v1/runtime/status (edge-guarded). We mock the REST module so the probe's+ // dependency is observable.+ const restMock = vi.hoisted(() => ({+ forwardHostHealth: vi.fn(),+ forwardHostStatus: vi.fn(),+ }))++ 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',+ headers: {},+ }++ beforeEach(() => {+ restMock.forwardHostHealth.mockReset()+ restMock.forwardHostStatus.mockReset()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ describe('probeHostReadyViaHealth', () => {+ it('probes /v1/runtime/health (not /v1/runtime/status) and returns true on a healthy answer', async () => {+ restMock.forwardHostHealth.mockResolvedValue({+ hostRef: 'chatllm',+ status: 'ok',+ observedAt: new Date().toISOString(),+ })++ const ready = await probeHostReadyViaHealth(HOST)++ expect(ready).toBe(true)+ expect(restMock.forwardHostHealth).toHaveBeenCalledTimes(1)+ expect(restMock.forwardHostHealth).toHaveBeenCalledWith(HOST)+ expect(restMock.forwardHostStatus).not.toHaveBeenCalled()+ })++ it('returns false when the health endpoint times out (AbortError)', async () => {+ const abort = new Error('The operation was aborted')+ abort.name = 'AbortError'+ restMock.forwardHostHealth.mockRejectedValue(abort)++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })++ it('returns false when the connection is refused (pod still suspended)', async () => {+ restMock.forwardHostHealth.mockRejectedValue(new TypeError('fetch failed'))++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })++ it('returns false when the health endpoint answers non-2xx (throws UpstreamHostError)', async () => {+ const upstream = Object.assign(new Error('Upstream host returned 503'), {+ name: 'UpstreamHostError',+ status: 503,+ bodySnippet: '',+ })+ restMock.forwardHostHealth.mockRejectedValue(upstream)++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })+ })diff --cc rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.tsindex 000000000,3ad2db1d7..03329a2bemode 000000,100644..100644--- a/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts+++ b/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts@@@ -1,0 -1,347 +1,351 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+ import type { ResolvedServerConnection, RpcAccessClaims, RpcScope } from '../../types.js'+ import {+ WakeAndHoldCoordinator,+ type WakeCoordinatorDeps,+ wakeCoordinationKey,+ } from '../wakeAndHold.js'++ // ── Issue #791 §11.1/§11.2/§13.3/§13.4 — principal-scoped wake coordination ──+ //+ // The old coordinator grouped by hostRef and picked the "latest by expiry"+ // authorization with NO principal/scope check. This suite pins the corrected+ // contract: coordination is keyed by principal + Host, only a same-principal+ // wake-capable authorization may occupy/replace the wake slot, non-wake tokens+ // never trigger a wake nor displace the wake authorization, and different+ // principals never share a group.++ const MAX_HOLD_MS = 90_000+ const POLL_MS = 2_000+ const RETRIGGER_MS = 15_000++ function conn(name = 'chatllm', url?: string): ResolvedServerConnection {+ return { name, url: url ?? `http://${name}:8080`, headers: {} }+ }++ function makeClaims(+ overrides: Partial<Omit<RpcAccessClaims, 'exp'>> & { expMs?: number } = {}+ ): RpcAccessClaims {+ const expMs = overrides.expMs ?? Date.now() + 3_600_000+ return {+ sub: overrides.sub ?? 'user-a',+ typ: overrides.typ ?? 'user',+ accessScope: overrides.accessScope ?? 'user',+ teamId: overrides.teamId ?? null,+ scopes: overrides.scopes ?? (['host:wake:write', 'host:message:invoke'] as RpcScope[]),+ hostRefs: overrides.hostRefs ?? ['chatllm'],+ jti: overrides.jti ?? 'jti-1',+ iat: 1,+ exp: Math.floor(expMs / 1000),+ }+ }++ function makeCoordinator(overrides?: Partial<WakeCoordinatorDeps>): {+ coordinator: WakeAndHoldCoordinator+ requestWake: ReturnType<typeof vi.fn>+ probeReady: ReturnType<typeof vi.fn>+ } {+ const requestWake = vi.fn().mockResolvedValue({ kind: 'wake-requested', wakeGeneration: 1 })+ const probeReady = vi.fn().mockResolvedValue(false)+ const coordinator = new WakeAndHoldCoordinator({+ requestWake,+ probeReady,+ maxHoldMs: MAX_HOLD_MS,+ pollMs: POLL_MS,+ retriggerMs: RETRIGGER_MS,+ maxTrackedCoordinations: 1_000,+ ...overrides,+ })+ return { coordinator, requestWake, probeReady }+ }++ function hold(+ coordinator: WakeAndHoldCoordinator,+ claims: RpcAccessClaims,+ token: string,+ host: ResolvedServerConnection = conn(),+ hostRef = 'chatllm'+ ) {+ return coordinator.hold({ hostRef, host, claims, rpcAccessToken: token })+ }++ let warnSpy: ReturnType<typeof vi.spyOn>+ let debugSpy: ReturnType<typeof vi.spyOn>+ let infoSpy: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ vi.useFakeTimers()+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => {})+ infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})+ })++ afterEach(() => {+ expect(vi.getTimerCount()).toBe(0) // no dangling timers, ever+ vi.useRealTimers()+ warnSpy.mockRestore()+ debugSpy.mockRestore()+ infoSpy.mockRestore()+ })++ 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'))+ })++ it('separates user, team, and service principals and never contains bearer material', () => {+ const user = makeClaims({ typ: 'user', accessScope: 'user', teamId: null, sub: 'u1' })+ const team = makeClaims({ typ: 'user', accessScope: 'team', teamId: 't1', sub: 'u1' })+ const service = makeClaims({ typ: 'service', accessScope: 'service', teamId: 't1', sub: 'svc' })+ const keys = [+ wakeCoordinationKey(user, 'chatllm'),+ wakeCoordinationKey(team, 'chatllm'),+ wakeCoordinationKey(service, 'chatllm'),+ ]+ expect(new Set(keys).size).toBe(3)+ for (const key of keys) expect(key).not.toContain('bearer')+ })+ })++ describe('§13.3 wake coordination matrix', () => {+ it('row 1: wake-capable A + non-wake A (later expiry) → retain A wake auth; add waiter only', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims({ scopes: ['host:wake:write', 'host:session:read'] })+ const pA = hold(coordinator, a, 'tok-wake')+ expect(requestWake).toHaveBeenCalledTimes(1)+ expect(requestWake).toHaveBeenCalledWith('chatllm', 'tok-wake')++ const nonWakeLater = makeClaims({+ scopes: ['host:session:read'],+ expMs: Date.now() + 7_200_000,+ })+ const pB = hold(coordinator, nonWakeLater, 'tok-nonwake')++ expect(coordinator.trackedCoordinationCount()).toBe(1) // same principal group+ expect(requestWake).toHaveBeenCalledTimes(1) // the non-wake waiter triggered NO new wake+ expect(requestWake).not.toHaveBeenCalledWith('chatllm', 'tok-nonwake')++ probeReady.mockResolvedValue(true)+ await vi.advanceTimersByTimeAsync(POLL_MS)+ const [oA, oB] = await Promise.all([pA, pB])+ expect(oA.kind).toBe('proceed')+ expect(oB.kind).toBe('proceed')+ })++ it('row 2: wake-capable A + fresher wake-capable A → replace wake authorization + connection', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims({ expMs: Date.now() + 1_000_000 })+ const pA = hold(coordinator, a, 'tok-a', conn('chatllm', 'http://chatllm-old:8080'))++ const fresher = makeClaims({ expMs: Date.now() + 2_000_000 })+ const freshHost = conn('chatllm', 'http://chatllm-fresh:8080')+ const pA2 = hold(coordinator, fresher, 'tok-a2', freshHost)++ // Readiness probe now uses the fresher connection.+ await vi.advanceTimersByTimeAsync(POLL_MS)+ expect(probeReady).toHaveBeenCalledWith(freshHost)+ // The next wake retrigger uses the fresher wake token.+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS)+ expect(requestWake).toHaveBeenCalledWith('chatllm', 'tok-a2')++ coordinator.drain()+ await Promise.all([pA, pA2])+ })++ it('row 3: user A / team 1 vs user A / team 2 → separate groups', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const t1 = makeClaims({ accessScope: 'team', teamId: 'team-1' })+ const t2 = makeClaims({ accessScope: 'team', teamId: 'team-2' })+ const p1 = hold(coordinator, t1, 'tok-t1')+ const p2 = hold(coordinator, t2, 'tok-t2')+ expect(coordinator.trackedCoordinationCount()).toBe(2)+ expect(requestWake).toHaveBeenCalledTimes(2)+ coordinator.drain()+ await Promise.all([p1, p2])+ })++ it('row 4: user A vs user B → separate groups', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const a = makeClaims({ sub: 'user-a' })+ const b = makeClaims({ sub: 'user-b' })+ const pa = hold(coordinator, a, 'tok-a')+ const pb = hold(coordinator, b, 'tok-b')+ expect(coordinator.trackedCoordinationCount()).toBe(2)+ expect(requestWake).toHaveBeenCalledTimes(2)+ coordinator.drain()+ await Promise.all([pa, pb])+ })++ it('row 5: no wake authorization + non-wake authorization → no unauthorized wake attempt', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const nonWake = makeClaims({ scopes: ['host:session:read'] })+ const outcome = await hold(coordinator, nonWake, 'tok-nonwake')+ expect(outcome.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalled()+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('key is delimiter-safe: boundary-shifting identifiers cannot collide two principals', () => {+ const p1 = makeClaims({ sub: 'a|team', accessScope: 'team', teamId: 'x' })+ const p2 = makeClaims({ sub: 'a', accessScope: 'team', teamId: 'team|x' })+ expect(wakeCoordinationKey(p1, 'chatllm')).not.toBe(wakeCoordinationKey(p2, 'chatllm'))+ })++ it('drain() is a terminal fence: a hold arriving after drain settles immediately and parks nothing', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ coordinator.drain('shutdown')+ const outcome = await hold(coordinator, makeClaims(), 'tok-after-drain')+ expect(outcome).toEqual({+ kind: 'waking',+ retryAfterMs: POLL_MS,+ reason: 'shutting-down',+ lastKnownState: 'unknown',+ })+ expect(requestWake).not.toHaveBeenCalled()+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('row 6: expired wake authorization + non-wake waiter → deterministic terminal, no wake', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ // Wake-capable token with a short budget (~2s) creates the group.+ const shortWake = makeClaims({+ scopes: ['host:wake:write', 'host:session:read'],+ expMs: Date.now() + 4_000,+ })+ const pShort = hold(coordinator, shortWake, 'tok-short')+ // A long-lived non-wake waiter keeps the entry alive after the wake token dies.+ const longNonWake = makeClaims({ scopes: ['host:session:read'], expMs: Date.now() + 3_600_000 })+ const pLong = hold(coordinator, longNonWake, 'tok-long')++ await vi.advanceTimersByTimeAsync(2_000) // short wake token budget expires+ expect((await pShort).kind).toBe('waking')+ expect(coordinator.trackedCoordinationCount()).toBe(1) // entry persists for the long waiter++ await vi.advanceTimersByTimeAsync(2_000) // now past the wake token's exp+ const late = makeClaims({ scopes: ['host:session:read'], expMs: Date.now() + 3_600_000 })+ const oLate = await hold(coordinator, late, 'tok-late')+ expect(oLate.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalledWith('chatllm', 'tok-late')++ coordinator.drain()+ await pLong+ })++ it('row 7: wake succeeds, health pending, several same-principal waiters → one wake, each proceeds', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims()+ const pendings = [+ hold(coordinator, a, 'tok-1'),+ hold(coordinator, a, 'tok-2'),+ hold(coordinator, a, 'tok-3'),+ ]+ expect(coordinator.trackedCoordinationCount()).toBe(1)+ expect(requestWake).toHaveBeenCalledTimes(1) // one wake sequence for the principal group++ probeReady.mockResolvedValue(true)+ await vi.advanceTimersByTimeAsync(POLL_MS)+ for (const outcome of await Promise.all(pendings)) {+ expect(outcome.kind).toBe('proceed')+ }+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('row 8: waiter settles, a later probe failure does not re-settle', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ void requestWake+ probeReady.mockResolvedValueOnce(true) // first probe: ready → settle proceed+ const pending = hold(coordinator, makeClaims(), 'tok-1')+ await vi.advanceTimersByTimeAsync(POLL_MS)+ expect((await pending).kind).toBe('proceed')+ expect(coordinator.trackedCoordinationCount()).toBe(0)++ // Advancing past every window makes NO further probe/settle — group is gone.+ const probeCalls = probeReady.mock.calls.length+ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS * 2)+ expect(probeReady.mock.calls.length).toBe(probeCalls)+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })+ })++ describe('§13.4 operation outcomes (unit level)', () => {+ it('active runtime → proceed immediately, no hold loop', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'active', wakeGeneration: null })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'proceed', lastKnownState: 'active' })+ expect(probeReady).not.toHaveBeenCalled()+ })++ it('stateful unavailable (not-stateless) → legacy, never a stateless wake hold', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'not-stateless' })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'legacy', reason: 'not-stateless' })+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('suspended + no wake grant → no fallback grant; deterministic legacy result', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const outcome = await hold(coordinator, makeClaims({ scopes: ['host:session:read'] }), 'tok')+ expect(outcome.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalled()+ })+ })++ describe('a mid-hold wake auth rejection distinguishes initial from retrigger', () => {+ it('an initial wake 403 settles the group legacy', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'auth', status: 403 })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'legacy', reason: 'wake-auth-403' })+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('a retrigger wake 403 does NOT collapse still-valid waiters (initial guard)', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ requestWake+ .mockResolvedValueOnce({ kind: 'wake-requested', wakeGeneration: 1 })+ .mockResolvedValue({ kind: 'auth', status: 403 }) // retrigger rejected+ probeReady.mockResolvedValue(false)++ const pending = hold(coordinator, makeClaims(), 'tok')+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS) // fire one retrigger (auth 403)+ // The group is still held (bounded by deadlines), not collapsed to legacy.+ expect(coordinator.trackedCoordinationCount()).toBe(1)++ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS)+ const outcome = await pending+ expect(outcome).toMatchObject({ kind: 'waking' })+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })+ })++ describe('shutdown drain', () => {+ it('settles every parked waiter deterministically and leaves no dangling timers', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ void requestWake+ void probeReady+ const a = hold(coordinator, makeClaims({ sub: 'user-a' }), 'tok-a', conn('chatllm'), 'chatllm')+ const b = hold(+ coordinator,+ makeClaims({ sub: 'user-b', hostRefs: ['other'] }),+ 'tok-b',+ conn('other'),+ 'other'+ )+ expect(coordinator.trackedCoordinationCount()).toBe(2)++ coordinator.drain()++ const [oa, ob] = await Promise.all([a, b])+ expect(oa.kind).toBe('waking')+ expect(ob.kind).toBe('waking')+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })+ })diff --cc rpc-proxy/src/services/wakeAndHold.tsindex 2a8d12c92,a60c3a9d1..a8b769594--- a/rpc-proxy/src/services/wakeAndHold.ts+++ b/rpc-proxy/src/services/wakeAndHold.ts@@@ -115,7 -217,10 +217,15 @@@ export class WakeAndHoldCoordinatorconst activeEntry = entryreturn await new Promise<WakeHoldOutcome>(resolve => {const id = ++this.waiterSeq- const timer = setTimeout(() => {- 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) return+ waiter.settled = trueactiveEntry.waiters.delete(id)resolve({kind: 'waking',diff --cc tests/e2e/gfsCopyFixtures.tsindex 000000000,5b50b1c8d..f139373cbmode 000000,100644..100644--- a/tests/e2e/gfsCopyFixtures.ts+++ b/tests/e2e/gfsCopyFixtures.ts@@@ -1,0 -1,310 +1,316 @@@+ import { seedGfsBlobWithKubectlCp } from './gfsBlobFixtureWriter'+ import {+ GFS_E2E_DRIVE,+ UUID_RE,+ assertFixtureName,+ firstDataLine,+ gfsWriterPod,+ kubectlContext,+ kubectlOut,+ ridOf,+ runControlPostgresSql,+ splitSqlRow,+ sqlLiteral,+ } from './gfsFixtureCore'+ import { cleanupGfsFixture } from './gfsResourceFixtures'++ export interface GfsCopyTreeFixture {+ sourceName: string+ destinationName: string+ sourceResourceId: string+ destinationResourceId: string+ standaloneFileName: string+ standaloneFileResourceId: string+ sourceUri: string+ destinationUri: string+ }++ export interface GfsTreeSnapshotNode {+ relativePath: string+ resourceId: string+ parentResourceId: string | null+ name: string+ kind: 'file' | 'directory'+ bytes: number+ version: number+ content: string | null+ }++ export interface GfsHostGrantRow {+ resourceId: string+ permissions: string[]+ inherit: boolean+ }++ export function cleanupGfsCopyTreeFixture(fixture: GfsCopyTreeFixture): void {+ const failures: string[] = []+ for (const name of [fixture.sourceName, fixture.destinationName]) {+ try {+ cleanupGfsFixture(name)+ } catch (error) {+ 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 {+ const row = firstDataLine(+ runControlPostgresSql(`+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)+ VALUES (${sqlLiteral(GFS_E2E_DRIVE)}, NULL, '', 'directory', '/')+ ON CONFLICT (drive) WHERE parent_resource_id IS NULL AND deleted_at IS NULL+ DO UPDATE SET updated_at = gfs_resources.updated_at+ RETURNING resource_id::text;+ `)+ )+ if (!UUID_RE.test(row)) throw new Error(`failed to resolve GFS drive root: ${row}`)+ return row+ }++ function insertResource(input: {+ parentId: string+ name: string+ kind: 'file' | 'directory'+ path: string+ content?: Buffer+ }): string {+ const content = input.content ?? Buffer.alloc(0)+ const row = firstDataLine(+ runControlPostgresSql(`+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, bytes)+ VALUES (+ ${sqlLiteral(GFS_E2E_DRIVE)}, ${sqlLiteral(input.parentId)}::uuid,+ ${sqlLiteral(input.name)}, ${sqlLiteral(input.kind)}, ${sqlLiteral(input.path)},+ ${input.kind === 'file' ? content.byteLength : 0}+ ) RETURNING resource_id::text;+ `)+ )+ if (!UUID_RE.test(row)) throw new Error(`failed to seed GFS resource ${input.path}: ${row}`)+ if (input.kind === 'file') {+ seedGfsBlobWithKubectlCp({+ context: kubectlContext(),+ writerPod: gfsWriterPod(),+ blobKey: ridOf(row),+ content,+ timeoutMs: 20_000,+ })+ }+ return row+ }++ /** Named precondition only: Copy and Rename are always performed by the agent. */+ export function seedGfsCopyTreeFixture(name: string): GfsCopyTreeFixture {+ assertFixtureName(name)+ const sourceName = `${name}-source`+ const destinationName = `${name}-destination`+ const standaloneFileName = 'standalone.txt'+ const seeded: string[] = []+ try {+ const rootId = driveRoot()+ const sourceResourceId = insertResource({+ parentId: rootId,+ name: sourceName,+ kind: 'directory',+ path: `/${sourceName}`,+ })+ seeded.push(sourceName)+ const destinationResourceId = insertResource({+ parentId: rootId,+ name: destinationName,+ kind: 'directory',+ path: `/${destinationName}`,+ })+ seeded.push(destinationName)+ const standaloneFileResourceId = insertResource({+ parentId: sourceResourceId,+ name: standaloneFileName,+ kind: 'file',+ path: `/${sourceName}/${standaloneFileName}`,+ content: Buffer.from(`issue-797 standalone ${name}\n`, 'utf8'),+ })+ const nestedId = insertResource({+ parentId: sourceResourceId,+ name: 'nested',+ kind: 'directory',+ path: `/${sourceName}/nested`,+ })+ insertResource({+ parentId: nestedId,+ name: 'empty',+ kind: 'directory',+ path: `/${sourceName}/nested/empty`,+ })+ insertResource({+ parentId: nestedId,+ name: 'alpha.txt',+ kind: 'file',+ path: `/${sourceName}/nested/alpha.txt`,+ content: Buffer.from(`issue-797 alpha ${name}\n`, 'utf8'),+ })+ const deeperId = insertResource({+ parentId: nestedId,+ name: 'deeper',+ kind: 'directory',+ path: `/${sourceName}/nested/deeper`,+ })+ insertResource({+ parentId: deeperId,+ name: 'beta.txt',+ kind: 'file',+ path: `/${sourceName}/nested/deeper/beta.txt`,+ content: Buffer.from(`issue-797 beta ${name}\n`, 'utf8'),+ })+ return {+ sourceName,+ destinationName,+ sourceResourceId,+ destinationResourceId,+ standaloneFileName,+ standaloneFileResourceId,+ sourceUri: `gfs://${GFS_E2E_DRIVE}/${ridOf(sourceResourceId)}`,+ destinationUri: `gfs://${GFS_E2E_DRIVE}/${ridOf(destinationResourceId)}`,+ }+ } catch (error) {+ const teardownFailures: string[] = []+ for (const fixtureName of seeded.reverse()) {+ try {+ cleanupGfsFixture(fixtureName)+ } catch (cleanupError) {+ teardownFailures.push(+ `${fixtureName}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`+ )+ }+ }+ if (teardownFailures.length > 0) {+ throw new Error(+ `GFS copy-tree seeding failed (${error instanceof Error ? error.message : String(error)}) ` ++ `AND teardown of partial state failed: ${teardownFailures.join('; ')}`+ )+ }+ throw error+ }+ }++ function readContent(resourceId: string, blobKey: string | null): string {+ const path = blobKey+ ? (() => {+ if (!/^[0-9a-f]{32}\/[0-9a-f-]{36}$/i.test(blobKey)) {+ throw new Error(`invalid GFS generation key in snapshot: ${blobKey}`)+ }+ return `/data/gfs/.generations/${blobKey}`+ })()+ : `/data/gfs/${ridOf(resourceId)}`+ return kubectlOut(['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'cat', path], 20_000)+ }++ export function getGfsTreeSnapshot(rootId: string): GfsTreeSnapshotNode[] {+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)+ const rows = runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id, parent_resource_id, name, kind, bytes, version, blob_key,+ '.'::text AS relative_path+ FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id, child.parent_resource_id, child.name, child.kind,+ child.bytes, child.version, child.blob_key, tree.relative_path || '/' || child.name+ FROM gfs_resources child JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL+ )+ SELECT relative_path || '|' || resource_id::text || '|' ||+ coalesce(parent_resource_id::text, '') || '|' || name || '|' || kind || '|' ||+ bytes::text || '|' || version::text || '|' || coalesce(blob_key, '')+ FROM tree ORDER BY relative_path;+ `)+ .split('\n')+ .map(line => line.trim())+ .filter(Boolean)++ return rows.map(row => {+ const parts = splitSqlRow(row)+ if (parts.length !== 8) throw new Error(`invalid GFS snapshot row shape: ${row}`)+ const [relativePath, resourceId, parentId, name, kind, bytes, version, blobKey] = parts as [+ string,+ string,+ string,+ string,+ string,+ string,+ string,+ string,+ ]+ if (!UUID_RE.test(resourceId) || (parentId && !UUID_RE.test(parentId))) {+ throw new Error(`invalid GFS snapshot row: ${row}`)+ }+ const normalizedKind = kind === 'directory' ? 'directory' : 'file'+ return {+ relativePath,+ resourceId,+ parentResourceId: parentId || null,+ name,+ kind: normalizedKind,+ bytes: Number(bytes),+ version: Number(version),+ content: normalizedKind === 'file' ? readContent(resourceId, blobKey || null) : null,+ }+ })+ }++ export function getGfsTreeAclShareCounts(rootId: string): { grants: number; shares: number } {+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)+ const row = firstDataLine(+ runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id FROM gfs_resources child+ JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL+ )+ SELECT (SELECT count(*) FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM tree))::text || '|' ||+ (SELECT count(*) FROM gfs_shares WHERE resource_id IN (SELECT resource_id FROM tree))::text;+ `)+ )+ const parts = splitSqlRow(row)+ if (parts.length !== 2) throw new Error(`invalid GFS ACL/share count row: ${row}`)+ const [grants, shares] = parts as [string, string]+ return { grants: Number(grants), shares: Number(shares) }+ }++ export function getGfsHostGrantsUnderTree(rootId: string, subjectId: string): GfsHostGrantRow[] {+ if (!UUID_RE.test(rootId) || !/^1st:[a-z0-9-]+\/[a-z0-9-]+$/.test(subjectId)) {+ throw new Error('invalid GFS host-grant tree query')+ }+ return runControlPostgresSql(`+ WITH RECURSIVE tree AS (+ SELECT resource_id FROM gfs_resources+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL+ UNION ALL+ SELECT child.resource_id FROM gfs_resources child+ JOIN tree ON child.parent_resource_id = tree.resource_id+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL+ )+ SELECT resource_id::text || '|' || array_to_string(permissions, ',') || '|' || inherit::text+ FROM 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 --cc tests/e2e/gfsResourceFixtures.tsindex 933644345,05d6d71de..6f97f4832--- a/tests/e2e/gfsResourceFixtures.ts+++ b/tests/e2e/gfsResourceFixtures.ts@@@ -41,12 -41,19 +41,16 @@@ function seedGfsBlob(resourceId: string}}- function cleanupGfsBlob(resourceId: string): void {- const blobKey = ridOf(resourceId)- kubectlOut(- ['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', `/data/gfs/${blobKey}`],- 20_000- )+ function cleanupGfsBlob(resourceId: string, blobKey?: string | null): void {+ const physicalPath = blobKey+ ? (() => {+ if (!/^[0-9a-f]{32}\/[0-9a-f-]{36}$/i.test(blobKey)) {+ throw new Error(`refusing to clean invalid GFS generation key: ${blobKey}`)+ }+ 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 {@@@ -188,7 -195,7 +192,8 @@@ export function seedGfsGrant(input:throw new Error(`subjectId is required for ${input.subjectType} GFS grants`)}const permissions = `ARRAY[${input.permissions.map(sqlLiteral).join(', ')}]::text[]`- runControlPostgresSql(`- const grantId = firstDataLine(runControlPostgresSql(`++ const grantId = firstDataLine(++ runControlPostgresSql(`INSERT INTO gfs_grants (drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by)@@@ -206,8 -213,11 +211,12 @@@permissions = EXCLUDED.permissions,inherit = EXCLUDED.inherit,granted_by = EXCLUDED.granted_by,- updated_at = now();+ updated_at = now()+ RETURNING id::text;- `))+ `)++ )+ if (!UUID_RE.test(grantId)) throw new Error(`failed to seed GFS grant: ${grantId}`)+ return grantId}export function getGfsGrantSummary(input: {@@@ -303,11 -345,15 +344,15 @@@ export function cleanupGfsFixture(name`).split('\n').map(line => line.trim())- .filter(line => UUID_RE.test(line))+ .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 of resourceIds) {+ for (const [resourceId, blobKey] of resources) {try {- cleanupGfsBlob(resourceId)+ cleanupGfsBlob(resourceId, blobKey || null)} catch (error) {cleanupErrors.push(error)}