UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

923 lines • 54.3 kB
import { posix } from "node:path";
import { isDeepStrictEqual } from "node:util";
import { foldDriveLetter, isWinFormPath } from "../tools/fs/safety.js";
import { parsePermissionRule, ruleSpellingOf, splitNamespacedName } from "@sema-agent/primitives";
import { callerToolNameProblem, NAMESPACED_NAME_SHAPES } from "./caller-tool-name.js";
import { compileAllowList, compiledEntryName, inertEntryPhrase, readRuleEntry, renderListEntry, rootFacingToolNames } from "./allow-entry.js";
import { valueTypeLabel } from "./tool-name-list.js";
import { retiredNameView } from "./tool-name-aliases.js";
import { NAME_RULE_FACES, noticeRuleText } from "./permission-rule-model.js";
import { namesASetOfTools } from "./namespaced-rule-name.js";
import { entriesNotAppliedDetail } from "./entries-not-applied.js";
import { callerKey } from "./caller-text.js";
import { optionKeys, receiveOptions, strayMembersOf } from "./own-property-receipt.js";
import { readPrincipal, readStoredPrincipal } from "./principal-name.js";
import { eraseStepOf, judgePrincipalRekey, readPrincipalRekeyInput, } from "./identity-rekey.js";
const SESSION_RULE_BUCKETS = { toolAllow: "allow", toolDeny: "deny", allowDirs: "dirs" };
const BUCKETS = Object.keys(SESSION_RULE_BUCKETS);
const BUCKET_WORDS = { toolAllow: "allow list", toolDeny: "deny list" };
const ENTRY_FIELDS = BUCKETS.filter((f) => SESSION_RULE_BUCKETS[f] !== "dirs");
const STORE_STAMPS = new Set(["rev", "gen", "grammar"]);
const OPERATOR_PART = "operatorRules";
export const SESSION_RULES_GRAMMAR = 8;
export class SessionPolicyError extends Error {
    code;
    detail;
    constructor(code, message, detail) {
        super(message);
        this.code = code;
        this.detail = detail;
        this.name = "SessionPolicyError";
    }
}
const NO_DECLARED_TOOLS = new Set();
const SESSION_POLICY_STORE_OPTION_KEYS = optionKeys()({ mountedToolNames: 0 });
export function readMountedToolNames(value) {
    if (value === undefined)
        return NO_DECLARED_TOOLS;
    const refuse = (why) => {
        throw new TypeError(`session rules store option mountedToolNames ${why} — it lists the names this deployment mounts its own tools under`);
    };
    if (typeof value === "string" || typeof value?.[Symbol.iterator] !== "function")
        refuse("must be an iterable of tool names (an array or a Set), not a single value");
    const names = new Set();
    for (const n of value) {
        if (typeof n !== "string")
            refuse(`holds ${JSON.stringify(n) ?? String(n)}, which is not a tool name`);
        const problem = callerToolNameProblem(n);
        if (problem !== undefined)
            refuse(`holds ${JSON.stringify(n)}: ${problem}`);
        names.add(n);
    }
    return names;
}
export function sessionRulesPrincipalOf(principal, verb) {
    const reading = readPrincipal(principal);
    if (reading.kind === "invalid")
        throw new TypeError(`SessionPolicyStore.${verb}: the principal must be a principal name or absent (got ${reading.fault}) — the empty string is absent; a provided value that names nobody is not "no principal"`);
    return reading.kind === "name" ? reading.name : undefined;
}
export function inheritedRuleKeyOf(entry) {
    if (entry.principal === undefined || readStoredPrincipal(entry.principal).kind !== "absent")
        return entry;
    const { principal: _absent, ...rest } = entry;
    return rest;
}
function conjoinBuckets(a, b) {
    const both = (x, y) => (x === undefined ? y?.slice() : y === undefined ? x.slice() : x.filter((e) => y.includes(e)));
    const either = (x, y) => (x === undefined && y === undefined ? undefined : [...new Set([...(x ?? []), ...(y ?? [])])]);
    const out = { toolAllow: both(a.toolAllow, b.toolAllow), toolDeny: either(a.toolDeny, b.toolDeny), allowDirs: both(a.allowDirs, b.allowDirs) };
    return Object.fromEntries(Object.entries(out).filter(([, v]) => v !== undefined));
}
export function conjoinSessionRuleRows(a, b) {
    const grammar = a.grammar ?? 0;
    if ((b.grammar ?? 0) !== grammar || [a, b].some((r) => r.operatorRules !== undefined && r.operatorRules.grammar !== grammar))
        return undefined;
    const bucketsOf = (r) => ({ ...(r.toolAllow !== undefined ? { toolAllow: r.toolAllow } : {}), ...(r.toolDeny !== undefined ? { toolDeny: r.toolDeny } : {}), ...(r.allowDirs !== undefined ? { allowDirs: r.allowDirs } : {}) });
    const lineOf = (r) => r.operatorRules ?? bucketsOf(r);
    const part = a.operatorRules === undefined && b.operatorRules === undefined ? undefined : { ...conjoinBuckets(lineOf(a), lineOf(b)), grammar };
    return { ...conjoinBuckets(a, b), ...(a.grammar !== undefined || b.grammar !== undefined ? { grammar } : {}), ...(part !== undefined ? { operatorRules: part } : {}) };
}
function lexWithin(root, p) {
    const fold = (x) => foldDriveLetter(isWinFormPath(x) ? x.replace(/\\/g, "/") : x);
    const nr = posix.normalize(fold(root)).replace(/\/+$/, "") || "/";
    const np = posix.normalize(fold(p)).replace(/\/+$/, "") || "/";
    if (nr === "/")
        return true;
    return np === nr || np.startsWith(nr + "/");
}
function isStoredRow(value) {
    const rev = value.rev;
    return typeof rev === "number" && Number.isInteger(rev) && rev >= 1;
}
function grammarOf(value) {
    const member = stampMemberOf(value);
    if (member.kind === "not_own_data") {
        return {
            got: member.got,
            sentence: `session rules carry a grammar stamp that is ${member.got} — grammar must be an own data member of the rules (the whole number of the rule grammar the entries are written in): ` +
                `an accessor is never called, and an inherited or non-enumerable member is not the value's own stamp`,
        };
    }
    const stamp = member.kind === "data" ? member.stamp : undefined;
    return readRuleGrammarStamp(stamp, stamp === undefined && isStoredRow(value) ? 0 : SESSION_RULES_GRAMMAR, { rules: "session rules", held: "entries" });
}
function stampMemberOf(value) {
    const own = Object.getOwnPropertyDescriptor(value, "grammar");
    if (own === undefined)
        return "grammar" in value ? { kind: "not_own_data", got: "an inherited member" } : { kind: "absent" };
    if (!("value" in own))
        return { kind: "not_own_data", got: "an accessor" };
    if (own.enumerable !== true)
        return { kind: "not_own_data", got: "a non-enumerable member" };
    return own.value === undefined ? { kind: "absent" } : { kind: "data", stamp: own.value };
}
export function readRuleGrammarStamp(stamp, absent, words) {
    if (stamp === undefined)
        return { grammar: absent };
    if (typeof stamp !== "number" || !Number.isInteger(stamp) || stamp < 0) {
        const got = typeof stamp === "number" ? "a number that is not a whole number of 0 or more" : valueTypeLabel(stamp);
        return { got, sentence: `${words.rules} carry a grammar stamp that is ${got} — the stamp is the whole number of the rule grammar the rules were written in (this engine reads grammar ${SESSION_RULES_GRAMMAR})` };
    }
    if (stamp > SESSION_RULES_GRAMMAR) {
        return {
            got: `${stamp}, a grammar newer than this engine's (${SESSION_RULES_GRAMMAR})`,
            sentence: `${words.rules} were written in rule grammar ${stamp}, newer than this engine reads (grammar ${SESSION_RULES_GRAMMAR}) — refusing rather than read their ${words.held} in an older grammar; an engine that reads grammar ${stamp} reads them`,
            later: true,
        };
    }
    return { grammar: stamp };
}
export function readSessionRulesShape(value) {
    const fault = (field, got, sentence) => ({ fault: { field, got }, sentence });
    if (typeof value !== "object" || value === null || Array.isArray(value)) {
        const got = Array.isArray(value) ? "an array" : valueTypeLabel(value);
        return fault("", got, `session rules must be an object of rule buckets (${BUCKETS.join(", ")}), got ${got}`);
    }
    const read = grammarOf(value);
    if ("got" in read)
        return fault("grammar", read.got, read.sentence);
    const rules = { grammar: read.grammar };
    for (const [key, v] of Object.entries(value)) {
        if (STORE_STAMPS.has(key) || v === undefined)
            continue;
        if (key === OPERATOR_PART) {
            const part = readOperatorPart(v);
            if ("fault" in part)
                return part;
            rules.operatorRules = part.rules;
            continue;
        }
        if (!Object.hasOwn(SESSION_RULE_BUCKETS, key)) {
            return fault(key, "not a rule bucket", `session rules hold ${callerKey(key)}, which is not a rule bucket — the buckets are ${BUCKETS.join(", ")}, and a shell command rule is a toolDeny / toolAllow entry written Bash(<command>) (Bash(rm:*) matches a command whose first word is rm)`);
        }
        const field = key;
        const listed = Array.isArray(v) ? Array.from(v) : undefined;
        const got = listed === undefined
            ? valueTypeLabel(v)
            : !listed.every((e) => typeof e === "string")
                ? "an array holding an entry that is not a string"
                : SESSION_RULE_BUCKETS[field] === "dirs" && listed.some((e) => e.trim() === "")
                    ? "an array holding an empty or blank entry"
                    : undefined;
        if (got !== undefined)
            return fault(field, got, `session rules ${field} must be an array of ${SESSION_RULE_BUCKETS[field] === "dirs" ? "directory paths" : "rule entries"}, got ${got} — a bucket is written as a list (["Bash(rm:*)"], not "Bash(rm:*)")`);
        rules[field] = listed;
    }
    return { rules };
}
function readOperatorPart(value) {
    const read = readSessionRulesShape(value);
    if ("fault" in read) {
        const field = read.fault.field === "" ? OPERATOR_PART : `${OPERATOR_PART}.${read.fault.field}`;
        return { fault: { field, got: read.fault.got }, sentence: `the session rules' operator part: ${read.sentence}` };
    }
    const { operatorRules: nested, ...part } = read.rules;
    const unstamped = stampMemberOf(value).kind === "absent";
    if (unstamped || nested !== undefined) {
        const got = unstamped ? "rules without a grammar stamp" : "an operator part of its own";
        return { fault: { field: OPERATOR_PART, got }, sentence: `session rules carry an operator part holding ${got} — the part is the rules the last operator write set, stamped with their grammar by the write judge` };
    }
    return { rules: part };
}
export function normalizeRules(rules) {
    return canonicalRules(shapeOrRefuse(rules));
}
function shapeOrRefuse(rules) {
    const read = readSessionRulesShape(rules);
    if ("fault" in read)
        throw new SessionPolicyError("invalid_shape", read.sentence, read.fault);
    return read.rules;
}
function canonicalRules(read) {
    const out = {};
    for (const field of BUCKETS) {
        const list = read[field];
        if (list === undefined)
            continue;
        out[field] = SESSION_RULE_BUCKETS[field] === "dirs" ? list.map((d) => posix.normalize(d).replace(/\/+$/, "") || "/") : [...list];
    }
    return out;
}
const NAMES_NO_TOOL = "an entry naming no tool, so it refused nothing";
const NO_RULE_THEN = (direction) => (direction === "allow" ? "no rule, so it admitted nothing" : "no rule, so the rules could not be read and refused every call");
const NAME_PATTERN_NOW = "a pattern over the whole tool name, every tool it matches";
function spellsWholeProtocol(name) {
    const split = splitNamespacedName(name);
    return split !== undefined && split.peer === "*" && (split.tool === undefined || split.tool === "*");
}
const GRAMMAR_REVISIONS = [
    {
        grammar: 1,
        answer: ({ direction, entry, reading }) => {
            const otherName = reading.kind === "row" ? compiledEntryName(reading.compiled) !== entry : reading.reason === "wildcard_all";
            if (!otherName)
                return undefined;
            if (direction === "allow")
                return { was: "a tool name compared as written, naming no tool", now: "the rule it spells", keep: { kind: "inert", reason: "earlier_grammar" }, reader: "named_no_tool" };
            return reading.kind === "row" ? { was: "a tool name compared as written, naming no tool, so it refused nothing", now: "the rule it spells", reader: "grammar_revised" } : undefined;
        },
    },
    {
        grammar: 3,
        answer: ({ direction, reading }) => direction === "deny" && reading.kind === "row" && reading.compiled.kind === "covering" && spellsWholeProtocol(reading.compiled.pattern)
            ? { was: NAMES_NO_TOOL, now: "a deny of every tool of the protocol", reader: "grammar_revised" }
            : undefined,
    },
    {
        grammar: 4,
        answer: ({ direction, reading }) => {
            if (reading.kind !== "row")
                return undefined;
            const { compiled } = reading;
            if (compiled.kind === "name" && NAME_RULE_FACES[compiled.rule.tool]?.values === "mounted") {
                return { was: direction === "allow" ? "an entry with no rule form, so it admitted nothing" : "an entry with no rule form, so it refused nothing", now: "a rule on the agent type it names", reader: "grammar_revised" };
            }
            return compiled.kind === "command" && compiled.rule.match === "pattern" ? { was: NO_RULE_THEN(direction), now: "the Bash pattern rule it spells", reader: "grammar_revised" } : undefined;
        },
    },
    {
        grammar: 5,
        answer: ({ row, direction, entry, reading, list }) => {
            if (direction === "allow") {
                if (row >= 1 && list.some(readsAsWildcard))
                    return { was: "voided by the `*` its list holds", now: "one entry that grants nothing, the entries beside it read as written", keep: { kind: "inert", reason: "wildcard_all" } };
                const parsed = reading.kind === "inert" ? ruleSpellingOf(entry) : undefined;
                const name = parsed?.ruleContent === undefined ? parsed?.toolName : undefined;
                if (name === undefined || name === "*" || !name.includes("*") || name.startsWith("*") || splitNamespacedName(name) !== undefined)
                    return undefined;
                return { was: `the exact tool name ${JSON.stringify(name)}`, now: "no rule (an allow reads a `*` only in a protocol name's tool segment)", keep: { kind: "row", compiled: { kind: "tool", name } }, reader: "grammar_revised" };
            }
            if (reading.kind !== "row" || reading.compiled.kind !== "covering")
                return undefined;
            const { pattern } = reading.compiled;
            const split = splitNamespacedName(pattern);
            if (!pattern.includes("*") || spellsWholeProtocol(pattern) || (split !== undefined && !split.peer.includes("*")))
                return undefined;
            const answer = { now: NAME_PATTERN_NOW, reader: "grammar_revised" };
            if (pattern === "*")
                return { ...answer, was: NAMES_NO_TOOL, keep: { kind: "inert", reason: "wildcard_all" } };
            if (split !== undefined)
                return { ...answer, was: NAMES_NO_TOOL, keep: { kind: "inert", reason: "namespace_wildcard" } };
            if (pattern.startsWith("*"))
                return { ...answer, was: NO_RULE_THEN(direction) };
            return { ...answer, was: `the exact tool name ${JSON.stringify(pattern)}, so it refused only a tool of that name`, keep: { kind: "row", compiled: { kind: "tool", name: pattern } } };
        },
    },
    {
        grammar: 7,
        answer: ({ direction, reading }) => {
            if (direction !== "deny" || reading.kind !== "row" || reading.compiled.kind !== "covering" || namesASetOfTools(reading.compiled.pattern, "deny"))
                return undefined;
            const { pattern } = reading.compiled;
            return {
                was: `the exact tool name ${JSON.stringify(pattern)}, so it refused only a tool of that name`,
                now: "every MCP server spelling the name can stand for — that tool, and every tool of a server whose own name carries the `__`",
                keep: { kind: "row", compiled: { kind: "tool", name: pattern } },
                reader: "grammar_revised",
            };
        },
    },
];
function earlierGrammarReads(row, direction, entry, reading, list, to = SESSION_RULES_GRAMMAR) {
    if (row >= SESSION_RULES_GRAMMAR)
        return { reading };
    let first;
    let last;
    let spanFirst;
    let spanLast;
    let kept;
    for (const revision of GRAMMAR_REVISIONS) {
        if (revision.grammar <= row)
            continue;
        const answer = revision.answer({ row, direction, entry, reading, list });
        if (answer === undefined)
            continue;
        first ??= answer;
        last = answer;
        if (revision.grammar <= to) {
            spanFirst ??= answer;
            spanLast = answer;
        }
        if (answer.keep !== undefined) {
            kept = answer.keep;
            break;
        }
    }
    const change = spanFirst !== undefined && spanLast !== undefined ? { change: { was: spanFirst.was, now: spanLast.now } } : {};
    const read = kept ?? reading;
    if (read.kind === "inert" && read.reason === "grammar")
        return { reading: { kind: "inert", reason: "earlier_grammar" }, reader: "no_rule", ...change };
    if (first === undefined || last === undefined)
        return { reading: read };
    const reader = first.reader === "named_no_tool" ? first.reader : last.reader;
    if (reader === undefined)
        return { reading: read, ...change };
    return { reading: read, reader, ...(reader === "grammar_revised" ? { revised: { was: first.was, now: last.now, stands: kept !== undefined } } : {}), ...change };
}
function rereadEntry(direction, entry, from, to, roster) {
    const current = readRuleEntry(entry, direction, roster, storeView(roster));
    const then = earlierGrammarReads(from.grammar, direction, entry, current, from.list, Math.max(from.grammar, to.grammar));
    const now = earlierGrammarReads(to.grammar, direction, entry, current, to.list);
    if (isDeepStrictEqual(then.reading, now.reading))
        return undefined;
    const words = from.grammar < to.grammar ? then.change : earlierGrammarReads(to.grammar, direction, entry, current, to.list, from.grammar).change;
    const swap = from.grammar > to.grammar && words !== undefined ? { was: words.now, now: words.was } : words;
    return { then: then.reading, now: now.reading, words: swap ?? { was: `as read in rule grammar ${from.grammar}`, now: `as read in rule grammar ${to.grammar}` } };
}
const NO_RULE_REASONS = new Set(["grammar", "earlier_grammar"]);
export function unreadableDenyEntries(rules, roster) {
    return compileSessionRuleBucket(rules, "toolDeny", roster).inert.filter((i) => NO_RULE_REASONS.has(i.reason));
}
const STAR_IS_NO_ALLOW_RULE = "it is no allow rule in any grammar and a write holding it is refused";
function starWayOut(onlyStars, others, left) {
    return onlyStars
        ? `"*" is no allow rule in any grammar (a write holding it is refused); to drop it, ${REWRITE_IN_CURRENT_GRAMMAR}; ${left}`
        : `${others}, leaving "*" out — ${STAR_IS_NO_ALLOW_RULE}; ${left}`;
}
function readsAsWildcard(entry) {
    return typeof entry === "string" && entry === entry.trim() && parsePermissionRule(entry).toolName === "*";
}
function entryBucketDirection(field) {
    const direction = SESSION_RULE_BUCKETS[field];
    if (direction === "allow" || direction === "deny")
        return direction;
    throw new SessionPolicyError("invalid_shape", `${JSON.stringify(field)} is no rule-entry bucket of the session rules — the entry buckets are ${ENTRY_FIELDS.join(" and ")}`);
}
function bucketReadings(rules, field, roster) {
    const direction = entryBucketDirection(field);
    const entries = rules[field] ?? [];
    const view = storeView(roster);
    return entries.map((entry) => ({ entry, ...earlierGrammarReads(rules.grammar, direction, entry, readRuleEntry(entry, direction, roster, view), entries) }));
}
export function compileSessionRuleBucket(rules, field, roster) {
    const rows = [];
    const inert = [];
    const earlier = [];
    for (const { entry, reading } of bucketReadings(rules, field, roster)) {
        if (reading.kind === "row")
            rows.push({ entry, compiled: reading.compiled });
        else {
            const { kind: _kind, ...why } = reading;
            void _kind;
            (why.reason === "earlier_grammar" ? earlier : inert).push({ entry, ...why });
        }
    }
    return { rows, inert: [...inert, ...earlier] };
}
export function earlierGrammarEntries(rules, field) {
    return bucketReadings(rules, field).flatMap((r) => (r.reader === undefined ? [] : [r.entry]));
}
const ADVISORY_ENTRIES_SHOWN = 5;
function shownEntries(entries, render) {
    const rest = entries.length > ADVISORY_ENTRIES_SHOWN ? ` and ${entries.length - ADVISORY_ENTRIES_SHOWN} more` : "";
    return `${entries.slice(0, ADVISORY_ENTRIES_SHOWN).map(render).join(", ")}${rest}`;
}
const REWRITE_IN_CURRENT_GRAMMAR = `rewrite the session's stored rules in the current rule grammar (${SESSION_RULES_GRAMMAR}): the same rules, with the entries that do nothing left out`;
function rewriteWayOutWord() {
    return { by: "rewrite_in_current_grammar", stampsGrammar: SESSION_RULES_GRAMMAR };
}
export function earlierGrammarAdvisory(sessionId, entries, field, grammar, part) {
    const read = earlierGrammarReadings(entries, field, grammar);
    const noRule = read.filter((r) => r.reader === "no_rule").map((r) => r.entry);
    const namedNoTool = read.filter((r) => r.reader === "named_no_tool").map((r) => r.entry);
    const revised = read.flatMap((r) => (r.revised === undefined ? [] : [{ entry: r.entry, ...r.revised }]));
    const says = (p) => part === undefined || part === p;
    const sentences = [
        ...(says("named_no_tool") && namedNoTool.length > 0 ? [namedNoToolInGrammar0(namedNoTool)] : []),
        ...(says("no_rule") && noRule.length > 0 ? [noRuleInThisGrammar(noRule, field, grammar)] : []),
        ...(says("revised") && revised.length > 0 ? [revisedSinceGrammar(revised, field, grammar)] : []),
    ];
    return `session permission rules${sessionId === undefined ? "" : ` of session ${JSON.stringify(sessionId)}`}: ${sentences.join(" ")}`;
}
function earlierGrammarReadings(entries, field, grammar) {
    const direction = entryBucketDirection(field);
    return entries.map((entry) => {
        const read = earlierGrammarReads(grammar, direction, entry, readRuleEntry(entry, direction), entries);
        return { entry, reader: read.reader ?? "no_rule", ...(read.revised !== undefined ? { revised: read.revised } : {}) };
    });
}
function revisedSinceGrammar(entries, field, grammar) {
    const one = entries.length === 1;
    const said = entries
        .slice(0, ADVISORY_ENTRIES_SHOWN)
        .map((e) => `${renderListEntry(e.entry)} meant ${e.was} there; this engine's rule grammar (${SESSION_RULES_GRAMMAR}) reads it as ${e.now}, and ${e.stands ? "the stored meaning stands" : "this grammar's reading applies"}`)
        .join("; ");
    const rest = entries.length > ADVISORY_ENTRIES_SHOWN ? `; and ${entries.length - ADVISORY_ENTRIES_SHOWN} more` : "";
    return (`${BUCKET_WORDS[field]} ${one ? "holds an entry" : "holds entries"} stored in rule grammar ${grammar}${grammar === 0 ? " (before the rule grammar stamp)" : ""} whose meaning a later grammar revised — ${said}${rest}. ` +
        `To give ${one ? "it" : "them"} this grammar's reading, write the session's rules declaring grammar ${SESSION_RULES_GRAMMAR}, accepting the new reading of each entry that write changes; left as stored, ${one ? "it reads" : "they read"} as said.`);
}
export function earlierGrammarNotices(input) {
    const { rulesSessionId, sessionId, entries, field, grammar } = input;
    const read = earlierGrammarReadings(entries, field, grammar);
    const of = (reader) => read.filter((r) => r.reader === reader).map((r) => ({ entry: noticeRuleText(r.entry), reader: r.reader }));
    const frame = { bucket: field, storedGrammar: grammar, rewrite: rewriteWayOutWord(), ...(rulesSessionId !== undefined ? { rulesSessionId, sessionId } : {}) };
    const notices = [];
    if (field === "toolAllow" && of("named_no_tool").length > 0) {
        notices.push({ code: "config.entries_not_applied", message: earlierGrammarAdvisory(rulesSessionId, entries, field, grammar, "named_no_tool"), detail: { ...entriesNotAppliedDetail("session_rule_named_no_tool", of("named_no_tool")), ...frame } });
    }
    if (field === "toolAllow" && of("no_rule").length > 0) {
        notices.push({ code: "config.entries_not_applied", message: earlierGrammarAdvisory(rulesSessionId, entries, field, grammar, "no_rule"), detail: { ...entriesNotAppliedDetail("session_rule_unread", of("no_rule")), ...frame } });
    }
    if (field === "toolDeny" && of("no_rule").length > 0) {
        notices.push({ code: "config.session_rules_earlier_grammar", message: earlierGrammarAdvisory(rulesSessionId, entries, field, grammar, "no_rule"), detail: { entries: of("no_rule"), ...frame } });
    }
    const revised = read.filter((r) => r.revised !== undefined).map((r) => ({ entry: noticeRuleText(r.entry), reader: r.reader }));
    if (revised.length > 0) {
        notices.push({ code: "config.session_rules_reread", message: earlierGrammarAdvisory(rulesSessionId, entries, field, grammar, "revised"), detail: { entries: revised, ...frame } });
    }
    return notices;
}
function namedNoToolInGrammar0(entries) {
    const one = entries.length === 1;
    const wildcard = entries.some(readsAsWildcard);
    const rules = entries.some((e) => !readsAsWildcard(e));
    const left = `left as stored, ${one ? "it keeps" : "they keep"} admitting nothing.`;
    const way = !wildcard
        ? `To make ${one ? "it an allow rule" : "them allow rules"}, ${REWRITE_IN_CURRENT_GRAMMAR}, then add ${one ? "it" : "them"} again declaring grammar ${SESSION_RULES_GRAMMAR}; ${left}`
        : starWayOut(!rules, `To make the parenthesized ones allow rules, ${REWRITE_IN_CURRENT_GRAMMAR}, then add them again declaring grammar ${SESSION_RULES_GRAMMAR}`, left);
    return (`${BUCKET_WORDS.toolAllow} ${shownEntries(entries, renderListEntry)} ${one ? "was" : "were"} stored before the rule grammar stamp, when session rules compared an entry as a tool name as written, so ${wildcard ? 'an entry that is no bare tool name (a parenthesized rule, or "*")' : "a parenthesized entry"} named no tool — ` +
        `${one ? "it admits" : "they admit"} nothing, as when written${wildcard ? "; the rest of the list is read as written, not voided" : ""}. ${way}`);
}
function noRuleInThisGrammar(entries, field, grammar) {
    const one = entries.length === 1;
    const stored = `${BUCKET_WORDS[field]} ${shownEntries(entries, (entry) => inertEntryPhrase({ entry, reason: "grammar" }))} ${one ? "was" : "were"} stored in rule grammar ${grammar}${grammar === 0 ? ", before the rule grammar stamp" : ""}, and this engine's rule grammar (${SESSION_RULES_GRAMMAR}) reads ${one ? "it" : "them"} as no rule`;
    if (SESSION_RULE_BUCKETS[field] === "deny") {
        const way = `have an operator write the session's rules declaring grammar ${SESSION_RULES_GRAMMAR}, leaving ${one ? "it" : "them"} out or spelling the tool's name as a rule spells one — the write judge refuses an entry it cannot read`;
        return `${stored}: rules whose deny list holds an entry no grammar reads cannot be read, so every call is refused until they are rewritten. To lift that, ${way}, and a non-operator write cannot loosen rules that refuse every call.`;
    }
    const stars = entries.filter(readsAsWildcard).length;
    const left = `left as stored, ${one ? "it keeps" : "they keep"} admitting nothing.`;
    const wayOut = stars === 0
        ? `To allow what ${one ? "it" : "they"} meant, ${REWRITE_IN_CURRENT_GRAMMAR} (${one ? "it is" : "they are"} left out), then add the tool's name as a rule spells one; ${left}`
        : starWayOut(stars === entries.length, `To allow what the others meant, ${REWRITE_IN_CURRENT_GRAMMAR}, then add each tool's name as a rule spells one`, left);
    return `${stored} — ${one ? "it admits" : "they admit"} nothing, and the rest of the list is read as written. ${wayOut}`;
}
export function earlierGrammarRefusalClause(entries, grammar) {
    if (entries.length === 0)
        return "";
    const read = earlierGrammarReadings(entries, "toolAllow", grammar);
    const noRule = read.filter((r) => r.reader === "no_rule").length;
    const namedNoTool = read.filter((r) => r.reader !== "no_rule").map((r) => r.entry);
    const stars = namedNoTool.filter(readsAsWildcard).length;
    const others = namedNoTool.length - stars;
    const named = [...(stars > 0 ? ['"*"'] : []), ...(others > 0 ? [`${others} parenthesized ${others === 1 ? "entry" : "entries"}`] : [])];
    const clauses = [
        ...(namedNoTool.length > 0 ? [`where ${named.join(" and ")} ${namedNoTool.length === 1 ? "names no tool and admits" : "name no tool and admit"} nothing`] : []),
        ...(noRule > 0 ? [`${namedNoTool.length > 0 ? "and " : "where "}${noRule} ${noRule === 1 ? "entry is" : "entries are"} no rule in this engine's rule grammar (${SESSION_RULES_GRAMMAR}) and ${noRule === 1 ? "admits" : "admit"} nothing`] : []),
    ];
    return `; the session's rules are stored in rule grammar ${grammar}, ${clauses.join(" ")}; the person can ${REWRITE_IN_CURRENT_GRAMMAR}, then add the rule again`;
}
export function earlierGrammarAnnouncer(sink) {
    const announced = new Set();
    return (entries, field, grammar) => {
        const key = JSON.stringify([field, grammar, entries]);
        if (entries.length === 0 || announced.has(key))
            return;
        announced.add(key);
        try {
            sink(entries, field, grammar);
        }
        catch {
        }
    };
}
function storeRoster(declared) {
    return rootFacingToolNames(declared);
}
function storeView(roster) {
    return roster === undefined ? undefined : retiredNameView(roster);
}
function effectiveEntries(rules, field, roster) {
    return compileSessionRuleBucket(rules, field, roster).rows.map((r) => r.entry);
}
function assertEntriesRead(rules, mountedToolNames, known, wayOut) {
    for (const field of ENTRY_FIELDS) {
        for (const { entry, reading: read, reader } of bucketReadings(rules, field, known)) {
            if (read.kind === "row")
                continue;
            const { kind: _kind, ...why } = read;
            void _kind;
            const way = why.reason === "earlier_grammar"
                ? reader === "no_rule"
                    ? ` These rules are written in grammar ${rules.grammar} (a stored row), and this engine's grammar (${SESSION_RULES_GRAMMAR}) reads this entry as no rule (grammar) — ` +
                        (field === "toolAllow" && readsAsWildcard(entry) ? `leave the entry out: it spells "*", and ${STAR_IS_NO_ALLOW_RULE}.` : "leave the entry out, or spell the tool's name as a rule spells one.")
                    : ` These rules are written in grammar ${rules.grammar} (a stored row from before the grammar stamp), in which this entry names no tool.` +
                        (readsAsWildcard(entry)
                            ? ` It is no allow rule in grammar ${SESSION_RULES_GRAMMAR} either (a write holding it is refused) — leave the entry out.`
                            : ` To make it an allow rule, write it declaring grammar ${SESSION_RULES_GRAMMAR}, or leave the entry out.`)
                : why.verdict === "retired" || why.reason === "near_miss"
                    ? ` If this deployment mounts its own tool under ${renderListEntry(entry)}, declare it in the store's mountedToolNames.`
                    : why.currentName === undefined
                        ? ` An entry is a tool name (Read; a protocol tool is named ${NAMESPACED_NAME_SHAPES}), a protocol namespace (mcp__<server>), or a rule in its tool's own grammar (Bash(<command>), Edit(<path>), Skill(<name>), WebFetch(domain:<host>)).`
                        : "";
            const sentence = why.guidance !== undefined ? ` — ${why.guidance}` : "";
            const does = SESSION_RULE_BUCKETS[field] === "allow"
                ? "admits nothing as written"
                : NO_RULE_REASONS.has(why.reason)
                    ? "refuses every call as stored (rules whose toolDeny holds an entry no grammar reads cannot be read) — a write holding it is refused"
                    : "refuses nothing as written";
            const carriedBy = why.reason === "near_miss" && why.currentName !== undefined && !mountedToolNames.has(why.currentName) ? { carriedBy: "catalog" } : {};
            const rewrite = wayOut();
            throw new SessionPolicyError("inert_entry", `session rules ${field} holds ${inertEntryPhrase({ entry, ...why, ...carriedBy })}, which ${does}${sentence}; nothing was written.${way}${rewriteSentence(rewrite)}`, {
                field,
                entry,
                ...why,
                ...(rewrite !== undefined ? { rewrite } : {}),
            });
        }
    }
}
function refuseUndeclaredGrammar(rules) {
    const sentence = undeclaredGrammarSentence(rules, "write");
    if (sentence !== undefined)
        throw new SessionPolicyError("grammar_required", sentence);
}
function undeclaredGrammarSentence(value, face) {
    if (typeof value !== "object" || value === null || Array.isArray(value))
        return undefined;
    if (stampMemberOf(value).kind !== "absent" || (face === "rewrite" && isStoredRow(value)))
        return undefined;
    return face === "write"
        ? `session rules carry no grammar stamp — a write declares the rule grammar its entries are written in (grammar: ${SESSION_RULES_GRAMMAR} is the grammar this engine reads; ` +
            `a stored row handed back keeps its own stamp, and one stored before the stamp was written in grammar 0); nothing was written`
        : `session rules carry no grammar stamp and are no stored row (no rev) — the rewrite reads a row as its store returned it, or a value that declares the rule grammar its entries are written in; nothing was rewritten`;
}
export function judgeSessionRulesWrite(prior, rules, opts, mountedToolNames = NO_DECLARED_TOOLS) {
    if (opts?.expectedRev !== undefined && (prior?.rev ?? 0) !== opts.expectedRev) {
        throw new SessionPolicyError("conflict", `session rules rev mismatch (expected ${opts.expectedRev}, have ${prior?.rev ?? 0})`);
    }
    refuseUndeclaredGrammar(rules);
    const read = shapeOrRefuse(rules);
    const posture = readRereadPosture(opts?.rereads);
    const clean = canonicalRules(read);
    const grammar = read.grammar;
    const roster = storeRoster(mountedToolNames);
    const wayOut = () => rewriteWayOut(prior, mountedToolNames);
    const keepWay = (keep) => () => {
        if (keep === undefined || keep === grammar)
            return undefined;
        try {
            judgeSessionRulesWrite(prior, { ...clean, grammar: keep }, opts?.operator === true ? { operator: true } : undefined, mountedToolNames);
            return keep;
        }
        catch (e) {
            if (e instanceof SessionPolicyError)
                return undefined;
            throw e;
        }
    };
    assertEntriesRead(read, mountedToolNames, roster, wayOut);
    if (prior === null) {
        refuseUnacceptedRereads(undefined, keepWay(undefined), read, posture, wayOut, roster);
        if (opts?.operator === true)
            return { ...clean, grammar };
        return { ...clean, grammar, operatorRules: isStoredRow(rules) ? operatorPartOf(read) : { grammar } };
    }
    if (opts?.operator === true) {
        const stored = readSessionRulesShape(prior);
        const kept = "fault" in stored ? undefined : stored.rules;
        refuseUnacceptedRereads(kept, keepWay(kept?.grammar), read, posture, wayOut, roster);
        return { ...clean, grammar };
    }
    const stored = readStoredOrRefuse(prior);
    const operatorRules = operatorPartOf(stored);
    if (assertsRules(operatorRules) && grammar < operatorRules.grammar) {
        const rewrite = wayOut();
        throw new SessionPolicyError("grammar_older_than_rules", `this write declares rule grammar ${grammar}, older than the grammar the stored rules it is compared against are written in (${operatorRules.grammar}) — ` +
            `a non-operator write is read in a grammar no older than those rules; re-read the stored rules and declare their grammar or a later one; nothing was written.${rewriteSentence(rewrite)}`, { declaredGrammar: grammar, rulesGrammar: operatorRules.grammar, ...(rewrite !== undefined ? { rewrite } : {}) });
    }
    const loosens = loosenReasons(operatorRules, { ...clean, grammar }, mountedToolNames);
    if (loosens.length > 0) {
        const rewrite = wayOut();
        throw new SessionPolicyError("loosen_forbidden", `a non-operator session-rule write may not loosen what an operator wrote; refused: ${loosens.join("; ")}${rewrite !== undefined ? "." : ""}${rewriteSentence(rewrite)}`, rewrite !== undefined ? { rewrite } : undefined);
    }
    refuseUnacceptedRereads(stored, keepWay(stored.grammar), read, posture, wayOut, roster);
    return { ...clean, grammar, operatorRules };
}
const REREAD_POSTURE_MEMBERS = { accept_listed: ["kind", "entries"], adopt_row: ["kind"] };
const ENTRY_REF_MEMBERS = ["field", "entry"];
function readRereadPosture(value) {
    if (value === undefined)
        return { kind: "ask" };
    const refuse = (got, sentence) => {
        throw new SessionPolicyError("invalid_shape", sentence ?? `the write's rereads must be { kind: "accept_listed", entries: [{ field, entry }] } (field ${ENTRY_FIELDS.join(" or ")}, entry the text as written) or { kind: "adopt_row" }, got ${got}`, { field: "rereads", got });
    };
    const strays = (given, subject, keys) => {
        const stray = strayMembersOf(given, { subject, unit: "member", moment: "at the session-rules write" }, keys);
        if (stray !== undefined)
            refuse(`${subject} holding a member it does not carry`, stray.sentence);
    };
    if (typeof value !== "object" || value === null || Array.isArray(value))
        return refuse(Array.isArray(value) ? "an array" : valueTypeLabel(value));
    const kind = value.kind;
    if (kind !== "accept_listed" && kind !== "adopt_row")
        return refuse(`an object whose kind is ${typeof kind === "string" ? JSON.stringify(kind) : valueTypeLabel(kind)}`);
    strays(value, `the write's rereads (${kind})`, REREAD_POSTURE_MEMBERS[kind]);
    if (kind === "adopt_row")
        return { kind };
    const listed = value.entries;
    if (!Array.isArray(listed))
        return refuse(`accept_listed whose entries is ${valueTypeLabel(listed)}`);
    const items = listed;
    const entries = Array.from(items, (item) => {
        const ref = item;
        if (typeof ref !== "object" || ref === null)
            return refuse("accept_listed whose entries hold an item that is not an object");
        strays(ref, "a listed entry of the write's rereads", ENTRY_REF_MEMBERS);
        if (typeof ref.field !== "string" || !ENTRY_FIELDS.includes(ref.field))
            return refuse("accept_listed whose entries hold an item whose field is no rule-entry bucket");
        if (typeof ref.entry !== "string")
            return refuse("accept_listed whose entries hold an item whose entry is not a string");
        return { field: ref.field, entry: ref.entry };
    });
    return { kind, entries };
}
function rereadsOfWrite(stored, next, roster) {
    if (stored === undefined || stored.grammar === next.grammar)
        return [];
    const out = [];
    for (const field of ENTRY_FIELDS) {
        const direction = entryBucketDirection(field);
        const before = stored[field] ?? [];
        const after = next[field] ?? [];
        for (const entry of new Set(after)) {
            if (!before.includes(entry))
                continue;
            const change = rereadEntry(direction, entry, { grammar: stored.grammar, list: before }, { grammar: next.grammar, list: after }, roster);
            if (change !== undefined)
                out.push({ field, entry, was: change.words.was, now: change.words.now });
        }
    }
    return out;
}
function refuseUnacceptedRereads(stored, keepWay, next, posture, wayOut, roster) {
    let accepted;
    switch (posture.kind) {
        case "adopt_row":
            return;
        case "ask":
            accepted = [];
            break;
        case "accept_listed":
            accepted = posture.entries;
            break;
        default:
            return assertNoPosture(posture);
    }
    const rereads = rereadsOfWrite(stored, next, roster);
    const key = (r) => JSON.stringify([r.field, r.entry]);
    const listed = new Set(accepted.map(key));
    const missing = rereads.filter((r) => !listed.has(key(r)));
    const reread = new Set(rereads.map(key));
    const extra = accepted.filter((a) => !reread.has(key(a)));
    if (missing.length === 0 && extra.length === 0)
        return;
    const rewrite = wayOut();
    const said = rereads
        .slice(0, ADVISORY_ENTRIES_SHOWN)
        .map((r) => `${r.field} ${renderListEntry(r.entry)} meant ${r.was} in grammar ${stored?.grammar}; grammar ${next.grammar} reads it as ${r.now}`)
        .join("; ");
    const over = stored === undefined ? "over no stored rules it can read" : `over session rules stored in grammar ${stored.grammar}`;
    const more = rereads.length > ADVISORY_ENTRIES_SHOWN ? `; and ${rereads.length - ADVISORY_ENTRIES_SHOWN} more` : "";
    const why = [
        ...(missing.length > 0 ? [`${missing.length} of them ${missing.length === 1 ? "is" : "are"} not accepted`] : []),
        ...(extra.length > 0 ? [`its accepted list names ${extra.length} ${extra.length === 1 ? "entry" : "entries"} this write does not reread (${shownEntries(extra.map((e) => e.entry), renderListEntry)})`] : []),
    ].join(", and ");
    const keep = keepWay();
    const ways = [...(keep !== undefined ? [{ by: "declare_stored_grammar", grammar: keep }] : []), { by: "accept_listed" }];
    const keepSaid = keep !== undefined ? `declare grammar ${keep}, the stored rules' own, and every carried entry keeps its stored reading; or ` : "";
    throw new SessionPolicyError("reread_not_accepted", `this write declares rule grammar ${next.grammar} ${over}${rereads.length > 0 ? `, and carries ${rereads.length === 1 ? "an entry" : "entries"} the two grammars read differently — ${said}${more}` : ""}; ${why}. ` +
        `To write it: ${keepSaid}send rereads { kind: "accept_listed", entries } naming exactly the entries this write rereads (${rereads.length === 0 ? "none, so send none" : "each above"}) to take grammar ${next.grammar}'s readings; nothing was written.${rewriteSentence(rewrite)}`, { rereads, accepted: accepted.map((a) => ({ field: a.field, entry: a.entry })), ways, ...(rewrite !== undefined ? { rewrite } : {}) });
}
function assertNoPosture(posture) {
    throw new SessionPolicyError("invalid_shape", `the write's rereads holds an arm the judge does not know`, { field: "rereads", got: valueTypeLabel(posture) });
}
function rewriteWayOut(prior, mountedToolNames) {
    if (prior === null)
        return undefined;
    const rewrite = rewriteSessionRules(prior, { mountedToolNames });
    const changes = rewrite.kind === "refused" || (rewrite.kind === "rewritten" && (rewrite.dropped.length > 0 || rewrite.fromGrammar < SESSION_RULES_GRAMMAR));
    return changes ? rewriteWayOutWord() : undefined;
}
function rewriteSentence(rewrite) {
    return rewrite === undefined ? "" : ` The stored rules can be carried into the current grammar first: ${REWRITE_IN_CURRENT_GRAMMAR}, then write the change declaring grammar ${rewrite.stampsGrammar}.`;
}
export function rewriteSessionRules(row, options) {
    const mountedToolNames = readMountedToolNames(options?.mountedToolNames);
    const roster = storeRoster(mountedToolNames);
    const undeclared = undeclaredGrammarSentence(row, "rewrite");
    if (undeclared !== undefined)
        return { kind: "unreadable", fault: { field: "grammar", got: "absent" }, sentence: undeclared };
    const shaped = readSessionRulesShape(row);
    if ("fault" in shaped)
        return { kind: "unreadable", fault: shaped.fault, sentence: shaped.sentence };
    const stored = shaped.rules;
    const rules = { grammar: SESSION_RULES_GRAMMAR };
    const dropped = [];
    const refused = [];
    for (const field of BUCKETS) {
        const list = stored[field];
        if (list === undefined)
            continue;
        if (SESSION_RULE_BUCKETS[field] === "dirs") {
            rules[field] = [...list];
            continue;
        }
        const entryField = field;
        const direction = entryBucketDirection(entryField);
        const kept = [];
        for (const entry of list) {
            const then = earlierGrammarReads(stored.grammar, direction, entry, readRuleEntry(entry, direction, roster, storeView(roster)), list).reading;
            if (then.kind === "inert") {
                if (direction === "deny" && NO_RULE_REASONS.has(then.reason))
                    refused.push({ field: entryField, entry, why: "unreadable_deny", remedy: "leave_out" });
                else
                    dropped.push({ field: entryField, entry });
                continue;
            }
            const change = rereadEntry(direction, entry, { grammar: stored.grammar, list }, { grammar: SESSION_RULES_GRAMMAR, list }, roster);
            if (change === undefined) {
                kept.push(entry);
                continue;
            }
            const remedy = direction === "deny" && change.now.kind === "row" ? "accept_reread" : "leave_out";
            refused.push({ field: entryField, entry, why: "not_proven", remedy, was: change.words.was, now: change.words.now });
        }
        rules[entryField] = kept;
    }
    if (refused.length > 0)
        return { kind: "refused", fromGrammar: stored.grammar, entries: refused, dropped };
    return { kind: "rewritten", fromGrammar: stored.grammar, rules, dropped };
}
function operatorPartOf(read) {
    const { operatorRules, ...whole } = read;
    const part = operatorRules ?? whole;
    return { ...canonicalRules(part), grammar: part.grammar };
}
function assertsRules(part) {
    return BUCKETS.some((b) => part[b] !== undefined);
}
function readStoredOrRefuse(prior) {
    const stored = readSessionRulesShape(prior);
    if ("fault" in stored) {
        throw new SessionPolicyError("corrupt", `the stored session rules cannot be read as rules (${stored.sentence}) — refusing to judge a non-operator write against them as fewer rules; an operator write replaces them`);
    }
    return stored.rules;
}
export function loosenReasons(priorValue, nextValue, mountedToolNames = NO_DECLARED_TOOLS) {
    const shapeOf = (side, value) => {
        const read = readSessionRulesShape(value);
        if ("fault" in read)
            throw new SessionPolicyError("invalid_shape", `the ${side} rules: ${read.sentence}`, read.fault);
        return read.rules;
    };
    const prior = shapeOf("prior", priorValue);
    const next = shapeOf("next", nextValue);
    const roster = storeRoster(mountedToolNames);
    if (unreadableDenyEntries(next, roster).length > 0)
        return [];
    const unreadPrior = unreadableDenyEntries(prior, roster);
    if (unreadPrior.length > 0) {
        return [`the prior rules refuse every call — their toolDeny holds ${shownEntries(unreadPrior.map((i) => i.entry), (entry) => inertEntryPhrase({ entry, reason: "grammar" }))}, which no grammar reads`];
    }
    const reasons = [];
    const keptDeny = new Set(effectiveEntries(next, "toolDeny", roster));
    for (const x of effectiveEntries(prior, "toolDeny", roster))
        if (!keptDeny.has(x))
            reasons.push(`removed toolDeny ${renderListEntry(x)}`);
    if (prior.toolAllow !== undefined) {
        if (next.toolAllow === undefined)
            reasons.push("removed toolAllow allowlist (all allowed)");
        else {
            const had = new Set(effectiveEntries(prior, "toolAllow", roster));
            for (const x of effectiveEntries(next, "toolAllow", roster))
                if (!had.has(x))
                    reasons.push(`widened toolAllow with ${renderListEntry(x)}`);
        }
    }
    const pd = prior.allowDirs;
    if (pd !== undefined && pd.length > 0) {
        const nd = next.allowDirs;
        if (nd === undefined || nd.length === 0)
            reasons.push("removed allowDirs confinement");
        else
            for (const dir of nd)
                if (!pd.some((d) => lexWithin(d, dir)))
                    reasons.push(`widened allowDirs with "${dir}"`);
    }
    return reasons;
}
export function continuesLineage(a, b) {
    return (a.gen ?? 0) === (b.gen ?? 0);
}
export class InMemorySessionPolicyStore {
    map = new Map();
    mountedToolNames;
    constructor(options) {
        const opts = receiveOptions(options, "InMemorySessionPolicyStore", SESSION_POLICY_STORE_OPTION_KEYS);
        this.mountedToolNames = readMountedToolNames(opts.mountedToolNames);
    }
    highWater = new Map();
    key(sessionId, principal) {
        return JSON.stringify([sessionId, principal ?? null]);
    }
    keyParts(k) {
        const parts = JSON.parse(k);
        if (Array.isArray(parts) && parts.length === 2 && typeof parts[0] === "string" && (typeof parts[1] === "string" || parts[1] === null))
            return [parts[0], parts[1]];
        throw new Error("InMemorySessionPolicyStore: a map key this store did not mint");
    }
    async getRules(sessionId, principal) {
        const r = this.map.get(this.key(sessionId, sessionRulesPrincipalOf(principal, "getRules")));
        return r ? structuredClone(r) : null;
    }
    async putRules(sessionId, principal, rules, opts) {
        const key = this.key(sessionId, sessionRulesPrincipalOf(principal, "putRules"));
        const prior = this.map.get(key);
        const clean = judgeSessionRulesWrite(prior ?? null, rules, opts, this.mountedToolNames);
        const mark = this.highWater.get(key) ?? { rev: 0, gen: 0 };
        const floor = Math.max(prior?.rev ?? 0, mark.rev);
        const gen = prior?.gen ?? mark.gen;
        const next = { ...structuredClone(clean), rev: floor + 1, gen };
        this.map.set(key, next);
        this.highWater.set(key, { rev: next.rev, gen: Math.max(gen, mark.gen) });
        return structuredClone(next);
    }
    async listBySession(sessionId) {
        const out = [];
        for (const [k, rules] of this.map) {
            const [sid, principal] = this.keyParts(k);
            if (sid === sessionId)
                out.push({ principal: principal ?? undefined, rules: structuredClone(rules) });
        }
        return out;
    }
    async deleteBySession(sessionId) {
        for (const [k, row] of [...this.map.entries()]) {
            const [sid] = this.keyParts(k);
            if (sid !== sessionId)
                continue;
            this.highWater.set(k, eraseStepOf(this.highWater.get(k) ?? null, { rev: row.rev, gen: row.gen ?? 0 }));
            this.map.delete(k);
        }
    }
    async rekeyPrincipal(input) {
        const { from, toPrincipal, mode } = readPrincipalRekeyInput("SessionPolicyStore.rekeyPrincipal", input);
        const source = from.kind === "principal" ? from.principal : null;
        const sessions = new Set();
        if (source !== toPrincipal) {
            for (const k of [...this.map.keys(), ...this.highWater.keys()]) {
                const [sid, principal] = this.keyParts(k);
                if (principal === source)
                    sessions.add(sid);
            }
        }
        const keys = [...sessions].sort().map((sid) => ({ ka: JSON.stringify([sid, source]), kb: JSON.stringify([sid, toPrincipal]) }));
        const rowOf = (k) => {
            const row = this.map.get(k);
            return row === undefined ? null : { readable: true, rev: row.rev, gen: row.gen ?? 0 };
        };
        const markOf = (k) => {
            const mark = this.highWater.get(k);
            return mark === undefined ? null : { stamp: mark, lineageLost: false, ...(mark.arrival !== undefined ? { arrival: mark.arrival } : {}) };
        };
        const { answer, writes } = judgePrincipalRekey(mode, toPrincipal, keys.map(({ ka, kb }) => ({ sourceRow: rowOf(ka), sourceMark: markOf(ka), targetRow: rowOf(kb), targetMark: markOf(kb) })));
        writes.forEach((write, i) => {
            if (write === undefined)
                return;
            const { ka, kb } = keys[i];
            switch (write.kind) {
                case "arrive": {
                    const at = write.record.at;
                    if (write.sourceMark !== null)
                        this.highWater.set(ka, { ...write.sourceMark, arrival: write.record });
                    this.highWater.set(kb, { rev: at.rev, gen: at.gen });
                    this.map.set(kb, { ...structuredClone(this.map.get(ka)), rev: at.rev, gen: at.gen });
                    return;
                }
                case "merge-marks":
                    this.highWater.set(kb, write.mark);
                    return;
                case "leave":
                    this.highWater.set(ka, { ...write.mark, arrival: write.record });
                    this.map.delete(ka);
                    return;
                case "withdraw":
                    if (write.targetMark !== undefined) {
                        this.highWater.set(kb, write.targetMark);
                        this.map.delete(kb);
                    }
                    this.highWater.set(ka, write.sourceMark);
                    return;
                default: {
                    const unhandled = write;
                    return unhandled;
                }
            }
        });
        return answer;
    }
}
export const __testables = { lexWithin };