// Resolve only a confirmed request's assigned coder and a host-recorded checkout. import { constants, openSync, closeSync, fstatSync, readFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; import { isAbsolute, join } from 'node:path'; import { workspaceDir } from '../../seat/src/session.mjs'; import { workspaceFiles } from '../../seat/src/workspace-files.mjs'; const id = s => typeof s === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(s) && s !== '..'; const unavailable = () => ({ available: false, entries: [], truncated: false, contentAvailable: false, observedAt: new Date().toISOString() }); const flags = constants.O_RDONLY | constants.O_NOFOLLOW; function proofFile(path) { // Evidence directories are host-owned, but do not let a substituted ancestor redirect a read. const fds = []; try { let dir = openSync('/', flags | constants.O_DIRECTORY); fds.push(dir); const parts = path.split('/').filter(Boolean), file = parts.pop(); if (!file || parts.some(p => p === '.' || p === '..') || file === '.' || file === '..') throw new Error('unsafe proof'); for (const part of parts) { dir = openSync(`/proc/self/fd/${dir}/${part}`, flags | constants.O_DIRECTORY); fds.push(dir); } const fd = openSync(`/proc/self/fd/${dir}/${file}`, flags); fds.push(fd); const st = fstatSync(fd); if (!st.isFile() || st.size > 1024 * 1024 || st.nlink !== 1) throw new Error('unsafe proof'); return readFileSync(fd, 'utf8'); } finally { for (const fd of fds.reverse()) closeSync(fd); } } export function requestWorkspace({ dataRoot, state, events }) { if (typeof dataRoot !== 'string' || !isAbsolute(dataRoot) || dataRoot.split('/').includes('..')) return unavailable(); if (!state || !id(state.business) || !id(state.request) || !id(state.project) || !id(state.pm) || !state.snapshot || !Array.isArray(state.tasks) || !state.tasks.length) return unavailable(); const binding = state.selection?.bindings?.filter(b => b.digest === state.plan_digest) ?? []; if (binding.length !== 1 || binding[0].plan.business !== state.business || binding[0].plan.request !== state.request || binding[0].plan.project !== state.project || binding[0].plan.staff?.pm !== state.pm || !id(binding[0].plan.staff?.coder)) return unavailable(); const coder = binding[0].plan.staff.coder; if (!Array.isArray(events) || events.length > 10000) return unavailable(); const rows = events.map(e => { try { return { ...e, body: typeof e.body === 'string' ? JSON.parse(e.body) : e.body }; } catch { return null; } }).filter(Boolean); for (const task of state.tasks) { if (typeof task !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,159}$/.test(task)) return unavailable(); const created = rows.find(e => e.kind === 'task.created' && e.actor_role === state.pm && e.subject === task && e.body?.request === state.request && e.body?.project_key === state.project && e.body?.requirement_snapshot === state.snapshot); const assigned = rows.findLast(e => e.kind === 'task.assigned' && e.subject === task); if (!created || assigned?.actor_role !== state.pm || assigned.body?.role !== coder) return unavailable(); } const root = workspaceDir(dataRoot, state.business, coder), checkout = join(root, state.project); if (/[\n\r;,]/.test(checkout)) return unavailable(); const launches = rows.filter(e => e.kind === 'session.launched' && e.actor_role === coder); if (launches.some(e => e.body?.thread)) return unavailable(); let proven = false; for (const e of launches.slice(-32)) { if (!id(e.subject)) continue; try { const bundle = join(dataRoot, 'launches', state.business, e.subject, 'bundle'); const manifest = JSON.parse(proofFile(join(bundle, 'manifest.json'))); if (manifest.business !== state.business || manifest.instance !== coder || manifest.run !== e.subject || !Array.isArray(manifest.projects) || !manifest.projects.includes(state.project)) continue; // The manifest projects field includes unsafe, kept entries. The host prompt records that // outcome; do not treat a kept entry as a verified checkout. const prompt = proofFile(join(bundle, 'prompt.md')); if (createHash('sha256').update(prompt).digest('hex') !== manifest.files?.['prompt.md']) continue; const lines = prompt.split('\n').filter(x => x.startsWith('- Project clones: ')); if (lines.length !== 1) continue; const items = lines[0].slice('- Project clones: '.length).split('; '); const item = items.find(x => x.startsWith(`${state.project} at ${checkout}, `)); if (item && (item.startsWith(`${state.project} at ${checkout}, on branch `) || item.startsWith(`${state.project} at ${checkout}, on no branch `))) proven = true; } catch { /* missing or unsafe evidence never selects a workspace */ } } if (!proven) return unavailable(); try { return workspaceFiles(checkout); } catch { return unavailable(); } }