import { recordWorkspaceConflict } from "./store.js";
export function findCoveringWorkspaceLease(input) {
    const allowedLeaseIds = input.leaseIds?.length ? new Set(input.leaseIds) : undefined;
    return input.leases.find((lease) => {
        if (lease.status !== "active")
            return false;
        if (input.owner && lease.owner !== input.owner)
            return false;
        if (allowedLeaseIds && !allowedLeaseIds.has(lease.lease_id))
            return false;
        if (!leaseModeCovers(input.access, lease.mode))
            return false;
        return workspacePathWithin(input.path, lease.path);
    });
}
export function missingActiveWorkspaceLeases(input) {
    return input.paths.filter((entry) => !findCoveringWorkspaceLease({
        path: entry.path,
        access: entry.access,
        leases: input.leases,
        owner: input.owner,
        leaseIds: input.leaseIds,
    }));
}
export function matchedWorkspaceLeaseIds(input) {
    const ids = new Set();
    for (const entry of input.paths) {
        const lease = findCoveringWorkspaceLease({
            path: entry.path,
            access: entry.access,
            leases: input.leases,
            owner: input.owner,
        });
        if (lease)
            ids.add(lease.lease_id);
    }
    return [...ids];
}
export function workspacePathWithin(requested, allowedPath) {
    const req = normalizeWorkspacePolicyPath(requested);
    const base = normalizeWorkspacePolicyPath(allowedPath);
    return base === "." || req === base || req.startsWith(`${base}/`);
}
export function normalizeWorkspacePolicyPath(value) {
    const normalized = value.trim().replaceAll("\\", "/").replace(/\/+/g, "/").replace(/\/$/, "").replace(/^\.\//, "");
    return normalized || ".";
}
export async function recordWorkspaceLeaseViolation(store, runId, input) {
    return recordWorkspaceConflict(store, runId, {
        kind: "lease_overlap",
        path: input.path,
        actors: [input.actor],
        lease_ids: input.lease_ids,
        summary: input.summary,
    });
}
function leaseModeCovers(access, leaseMode) {
    if (access === "write")
        return leaseMode === "write";
    if (access === "append")
        return leaseMode === "write" || leaseMode === "append";
    return false;
}
//# sourceMappingURL=enforcement.js.map