UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,200 lines • 63.1 kB
import { randomBytes } from "node:crypto";
import { insidePeerOfferOf } from "./a2a-bound-grant.js";
import { COMMAND_RULE_TOOL, a2aWholePeerName, cardRuleFormOf, escapeForDisclosure, isAddStamp, foldSpacing, formatRuleText, hasUnrenderableCharacters, parseRuleText, READ_RULE_TOOL, ruleAdmitsCommand, cautionsSeatOf, ruleBasesNeeded, ruleBreadthWarningsOf, segmentCoverageOf, suggestRuleForHost, suggestRuleForName, suggestRuleForTool, suggestRulesForCommand, EDITED_RULE_BREADTH_WARNING_CODES, RULE_OFFER_KINDS, UNCOVERED_SEGMENT_REASONS, RULE_BEHAVIORS, RULE_BEHAVIOR_PRECEDENCE, isRuleBehavior, } from "./permission-rule-model.js";
import { readRecordedRuleOwner, readRuleOwner, sameRuleOwner } from "./rule-owner.js";
import { principalNameOf, readPrincipal } from "./principal-name.js";
import { isPlainRecord } from "./mods/kernel/receive.js";
import { effectiveOrThrow } from "./permission-rule-provider.js";
import { errText, isValidConsentScope, landRuleAdd, sameScope, writerOf } from "./permission-rule-store.js";
const isUncoveredSegmentReason = (v) => UNCOVERED_SEGMENT_REASONS.some((word) => v === word);
function candidateStampOf(cand) {
    return typeof cand === "object" && cand !== null && Object.hasOwn(cand, "peerFingerprint") ? { value: cand.peerFingerprint } : undefined;
}
function namesCandidate(rec, index) {
    return typeof index === "number" && Number.isSafeInteger(index) && index >= 0 && index < rec.candidates.length;
}
function boundStampOf(rec, offer, member) {
    const cand = rec.candidates[member];
    const own = candidateStampOf(cand);
    if (own === undefined || cand === undefined)
        return {};
    const edited = rec.edited;
    const unedited = edited === undefined || (typeof edited === "object" && edited !== null && namesCandidate(rec, edited.index) && edited.index !== member);
    const read = parseRuleText(cand.rule, cand.behavior);
    const whole = "rule" in read && a2aWholePeerName(read.rule.rule) !== undefined;
    return rec.kind === "card" && typeof rec.command !== "string" && offer.kind === "single" && unedited && cand.behavior === "allow" && whole && isAddStamp(own.value) ? { stamp: own.value } : { misplaced: true };
}
export const RULE_APPROVAL_KINDS = Object.freeze(["card", "import", "starter"]);
export const RULE_APPROVAL_STATES = Object.freeze(["pending", "approved", "redeemed"]);
const RECORD_OPTION_MEMBERS = { single: ["kind", "candidate"], batch: ["kind", "candidates", "segments", "uncoveredSegments", "uncoveredDetail"] };
export function readRuleOffer2(raw) {
    if (!isPlainRecord(raw))
        return { problem: "malformed" };
    const kind = raw.kind;
    if (typeof kind !== "string")
        return { problem: "malformed" };
    const word = RULE_OFFER_KINDS.find((k) => k === kind);
    if (word === undefined)
        return { problem: "unknown_word" };
    const declared = RECORD_OPTION_MEMBERS[word];
    if (Object.keys(raw).some((name) => !declared.includes(name)))
        return { problem: "malformed" };
    switch (word) {
        case "single": {
            const candidate = raw.candidate;
            return isCandidateIndex(candidate) ? { offer: { kind: "single", candidate } } : { problem: "malformed" };
        }
        case "batch": {
            const candidates = indexListOf(raw.candidates);
            if (candidates === undefined || candidates.length === 0)
                return { problem: "malformed" };
            const segments = raw.segments;
            const uncoveredSegments = raw.uncoveredSegments;
            const detail = raw.uncoveredDetail;
            const segmentList = segments === undefined ? undefined : stringListOf(segments);
            if (segments !== undefined && segmentList === undefined)
                return { problem: "malformed" };
            if (uncoveredSegments !== undefined && !isCandidateIndex(uncoveredSegments))
                return { problem: "malformed" };
            const rows = detail === undefined ? undefined : reasonRowsOf(detail);
            if (rows !== undefined && "problem" in rows)
                return rows;
            return {
                offer: {
                    kind: "batch",
                    candidates,
                    ...(segmentList !== undefined ? { segments: segmentList } : {}),
                    ...(uncoveredSegments !== undefined ? { uncoveredSegments } : {}),
                    ...(rows !== undefined ? { uncoveredDetail: rows.rows } : {}),
                },
            };
        }
        default: {
            const unhandled = word;
            return unhandled;
        }
    }
}
function isCandidateIndex(value) {
    return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}
function indexListOf(value) {
    if (!Array.isArray(value))
        return undefined;
    const length = value.length;
    const out = [];
    for (let i = 0; i < length; i++) {
        const item = value[i];
        if (!isCandidateIndex(item))
            return undefined;
        out.push(item);
    }
    return out;
}
function stringListOf(value) {
    if (!Array.isArray(value))
        return undefined;
    const length = value.length;
    const out = [];
    for (let i = 0; i < length; i++) {
        const item = value[i];
        if (typeof item !== "string")
            return undefined;
        out.push(item);
    }
    return out;
}
function reasonRowsOf(value) {
    if (!Array.isArray(value))
        return { problem: "malformed" };
    const length = value.length;
    const rows = [];
    for (let i = 0; i < length; i++) {
        const row = value[i];
        if (!isPlainRecord(row) || Object.keys(row).some((name) => name !== "segment" && name !== "reason"))
            return { problem: "malformed" };
        const segment = row.segment;
        const reason = row.reason;
        if (typeof segment !== "string" || typeof reason !== "string")
            return { problem: "malformed" };
        const word = UNCOVERED_SEGMENT_REASONS.find((r) => r === reason);
        if (word === undefined)
            return { problem: "unknown_word" };
        rows.push({ segment, reason: word });
    }
    return { rows };
}
export const RULE_APPROVAL_RECORD_SCHEMA = 4;
export class InMemoryRuleApprovalRecordStore {
    rows = new Map();
    async get(id) {
        const r = this.rows.get(id);
        if (r === undefined)
            return undefined;
        if (r.schema !== RULE_APPROVAL_RECORD_SCHEMA) {
            return {
                staleSchema: true,
                id: r.id,
                ...(typeof r.principal === "string" ? { principal: r.principal } : {}),
                ...(r.owner !== undefined ? { owner: structuredClone(r.owner) } : {}),
            };
        }
        return structuredClone(r);
    }
    async create(record) {
        if (this.rows.has(record.id))
            throw new Error(`approval record ${record.id} already exists`);
        this.rows.set(record.id, structuredClone(record));
    }
    async cas(id, expectRev, next) {
        const cur = this.rows.get(id);
        if (cur === undefined || cur.rev !== expectRev)
            return false;
        this.rows.set(id, structuredClone(next));
        return true;
    }
    size() {
        return this.rows.size;
    }
}
function nowIso(deps) {
    return (deps.now?.() ?? new Date()).toISOString();
}
function mintId(deps, prefix) {
    if (deps.newId !== undefined)
        return deps.newId();
    return `${prefix}_${Date.now().toString(36)}_${randomBytes(9).toString("base64url")}`;
}
function requirePrincipal(principal, entry) {
    const name = principalNameOf(principal);
    if (name === undefined) {
        throw new Error(`${entry} requires a verified principal — refusing to create an approval record without one`);
    }
    return name;
}
function resolveCallerOwner(principal, owner, entry) {
    if (owner !== undefined) {
        const given = readRuleOwner(owner);
        if (given === undefined) {
            throw new Error(`${entry} requires a verified principal or the local owner — the owner given is neither (a principal owner names a principal name)`);
        }
        if (given.kind === "principal") {
            if (readPrincipal(principal).kind !== "absent" && principal !== given.principal) {
                throw new Error(`${entry}: contradictory identity — principal "${principal}" and owner principal "${given.principal}" disagree`);
            }
            return given;
        }
        if (readPrincipal(principal).kind !== "absent") {
            throw new Error(`${entry}: contradictory identity — a principal and a local-owner were both given; a bucket has one owner`);
        }
        return given;
    }
    return { kind: "principal", principal: requirePrincipal(principal, entry) };
}
function ownerOfRecord(rec) {
    const stated = rec.owner;
    const owner = stated === undefined ? undefined : readRecordedRuleOwner(stated);
    if (stated !== undefined && owner === undefined)
        return undefined;
    const principal = rec.principal;
    const given = typeof principal === "string" && principal !== "";
    const named = given ? readRecordedRuleOwner({ kind: "principal", principal }) : undefined;
    if (given && named === undefined)
        return undefined;
    if (owner === undefined)
        return named;
    if (named !== undefined && !sameRuleOwner(owner, named))
        return undefined;
    return owner;
}
function recordIdentityOf(owner) {
    return owner.kind === "principal" ? { principal: owner.principal } : { owner: { kind: "local-owner" } };
}
function storeForOwner(provider, owner) {
    if (owner.kind === "principal")
        return provider.forPrincipal(owner.principal);
    const store = provider.forLocalOwner?.();
    if (store === undefined) {
        throw new Error("this deployment's permission-rule provider has no local-owner bucket (forLocalOwner is not implemented)");
    }
    return store;
}
function isStale(rec) {
    return rec.staleSchema === true;
}
const STALE_RECORD_MESSAGE = "this approval record predates the current record form, and the decision it carried is void — re-trigger the command to draw a fresh card";
function offerMembersOf(offer) {
    return offer.kind === "single" ? [offer.candidate] : offer.candidates;
}
function approvalRecordDamageOf(rec) {
    if (!Array.isArray(rec.candidates))
        return "the record carries no candidate list";
    if (!Array.isArray(rec.offers) || rec.offers.length === 0)
        return "the record carries no offers";
    const claimed = new Set();
    for (const [at, stored] of rec.offers.entries()) {
        const read = readRuleOffer2(stored);
        if ("problem" in read) {
            return `offer ${at} is not a record option this engine reads (${read.problem}): an option is an object whose kind is ${RULE_OFFER_KINDS.join(" or ")}, whose candidate indices are non-negative integers (a batch with no members is not one), whose reason rows are segment/reason rows from the closed reason set, and which carries no other member`;
        }
        const offer = read.offer;
        const members = offerMembersOf(offer);
        const seen = new Set();
        for (const member of members) {
            if (rec.candidates[member] === undefined) {
                return `offer ${at} references candidate ${member}, which the record does not carry`;
            }
            const cand = rec.candidates[member];
            if (typeof cand !== "object" || cand === null || typeof cand.rule !== "string") {
                return `offer ${at} references candidate ${member}, which is not a candidate row`;
            }
            if (!isRuleBehavior(cand.behavior)) {
                return `offer ${at} references candidate ${member}, whose behavior is not one of ${RULE_BEHAVIORS.join("/")}`;
            }
            if (rec.kind === "card" && cand.behavior !== "allow") {
                return `card offer ${at} references candidate ${member}, a ${cand.behavior} rule — a card mints allow candidates only`;
            }
            if (rec.kind === "card") {
                const read = parseRuleText(cand.rule, cand.behavior);
                if ("rule" in read && read.rule.match === "tool" && (typeof rec.command === "string" || cardRuleFormOf(read.rule.tool) !== "tool")) {
                    return `card offer ${at} references candidate ${member}, the whole-tool rule "${escapeForDisclosure(read.rule.rule)}" — the engine mints one only on the whole-tool card of a tool with no rule grammar`;
                }
            }
            if ("misplaced" in boundStampOf(rec, offer, member)) {
                return `offer ${at} references candidate ${member}, which carries an identity stamp the engine mints only on a card's single, unedited whole-peer allow candidate (a2a__<peer>), as a non-empty bounded string`;
            }
            if (!isValidConsentScope(cand.scope)) {
                return `offer ${at} references candidate ${member}, whose scope is not a consent-face scope (global, project, or session)`;
            }
            if (seen.has(member))
                return `batch offer ${at} references candidate ${member} twice`;
            seen.add(member);
            if (claimed.has(member))
                return `candidate ${member} belongs to more than one offer`;
            claimed.add(member);
        }
        if (offer.kind === "batch") {
            if (rec.kind === "card") {
                if (offer.segments === undefined || offer.segments.length !== offer.candidates.length) {
                    return `card batch offer ${at} must carry exactly one source segment per member`;
                }
                if (offer.uncoveredSegments === undefined) {
                    return `card batch offer ${at} must carry a non-negative uncovered-segment count`;
                }
                const detail = offer.uncoveredDetail;
                if (detail === undefined)
                    return `card batch offer ${at} must carry its uncovered-segment reason rows`;
                if (detail.length !== offer.uncoveredSegments) {
                    return `card batch offer ${at} carries ${detail.length} reason rows for an uncovered-segment count of ${offer.uncoveredSegments} — one fact, two seats, and they must agree`;
                }
                if (detail.length > 0) {
                    const rows = detail;
                    const table = typeof rec.command === "string" ? segmentCoverageOf(rec.command, { persisted: [] }, { tool: COMMAND_RULE_TOOL, cwd: undefined }) : undefined;
                    if (table === undefined) {
                        return `card batch offer ${at} carries reason rows but the record's command cannot back them — a row without a readable source command is a row nobody can audit`;
                    }
                    let cursor = 0;
                    for (const [ri, row] of rows.entries()) {
                        let found = -1;
                        for (let j = cursor; j < table.length; j++) {
                            if (table[j]?.segment === row.segment) {
                                found = j;
                                break;
                            }
                        }
                        if (found === -1)
                            return `card batch offer ${at} reason row ${ri} names a segment the record's command does not carry at or after that position`;
                        cursor = found + 1;
                    }
                }
            }
            else if (offer.segments !== undefined || offer.uncoveredSegments !== undefined || offer.uncoveredDetail !== undefined) {
                return `${escapeForDisclosure(rec.kind)} batch offer ${at} must not carry segment metadata — there is no compound command behind it`;
            }
        }
    }
    for (const [at] of rec.candidates.entries()) {
        if (!claimed.has(at))
            return `candidate ${at} belongs to no offer — every candidate row is claimed by exactly one offer`;
    }
    if (rec.edited !== undefined) {
        if (typeof rec.edited !== "object" || rec.edited === null)
            return "the edited seat is not an object";
        if (!namesCandidate(rec, rec.edited.index))
            return "the edited seat's index names no candidate row of the record";
        const w = rec.edited.warnings;
        if (w !== undefined) {
            if (!Array.isArray(w) || w.length !== 1 || !EDITED_RULE_BREADTH_WARNING_CODES.some((code) => w[0] === code)) {
                return "the edited seat's warnings are not a single-code array from the closed breadth-code set";
            }
        }
    }
    return undefined;
}
export function ruleOffersOfRecord(rec) {
    const stampOf = (offer, member) => {
        const bound = boundStampOf(rec, offer, member);
        if ("misplaced" in bound)
            throw new Error(`approval-record offer references candidate ${member}, which carries an identity stamp the engine mints only on a card's single, unedited whole-peer allow candidate — refusing to render it`);
        return bound.stamp !== undefined ? { peerFingerprint: bound.stamp } : {};
    };
    const tripleOf = (index) => {
        const cand = rec.candidates[index];
        const text = cand?.rule;
        if (cand === undefined || text === undefined)
            throw new Error(`approval-record offer references candidate ${index}, which the record does not carry`);
        const parsed = parseRuleText(text, cand.behavior);
        if ("reject" in parsed) {
            throw new Error(`approval-record candidate ${index} does not parse as a rule (${parsed.reject.code}) — refusing to render it as one`);
        }
        return { rule: parsed.rule.rule, match: parsed.rule.match, command: parsed.rule.command };
    };
    return rec.offers.map((offer) => {
        if (offer.kind === "single") {
            const t = tripleOf(offer.candidate);
            if (t.match === "subpath") {
                throw new Error("approval-record single offer references a directory rule — a shape this engine does not mint; refusing to render it");
            }
            return { kind: "single", ...t, ...cautionsSeatOf(t.match, t.command), ...stampOf(offer, offer.candidate) };
        }
        for (const member of offer.candidates)
            stampOf(offer, member);
        const segments = offer.segments;
        if (segments === undefined || offer.uncoveredSegments === undefined || offer.uncoveredDetail === undefined) {
            throw new Error("a batch offer without mint-time segment metadata has no card face to project — import/starter batches render as previews, not offer cards");
        }
        const rawDetail = offer.uncoveredDetail;
        const count = offer.uncoveredSegments;
        const detail = [];
        const detailDamaged = (() => {
            if (!Array.isArray(rawDetail) || !Number.isInteger(count) || count < 0 || rawDetail.length !== count)
                return true;
            for (let i = 0; i < rawDetail.length; i++) {
                const row = rawDetail[i];
                if (typeof row !== "object" || row === null)
                    return true;
                const segment = row.segment;
                const reason = row.reason;
                if (typeof segment !== "string" || !isUncoveredSegmentReason(reason))
                    return true;
                detail.push({ segment, reason });
            }
            return false;
        })();
        if (detailDamaged) {
            throw new Error("a batch offer's uncovered-segment reason rows do not match their count or the closed reason set — refusing to render damaged mint-time facts as a card face");
        }
        return {
            kind: "batch",
            rules: offer.candidates.map((candidate, i) => {
                const segment = segments[i];
                if (segment === undefined)
                    throw new Error(`batch offer member ${i} has no source segment recorded`);
                const t = tripleOf(candidate);
                return t.match === "subpath"
                    ? { kind: "directoryRead", rule: t.rule, directory: t.command, segment }
                    : { kind: "command", rule: t.rule, match: t.match, command: t.command, segment, ...cautionsSeatOf(t.match, t.command) };
            }),
            uncoveredSegments: count,
            uncoveredDetail: detail,
        };
    });
}
export function mintRuleTicket(recordId, candidateIndex) {
    return `rt.${candidateIndex}.${recordId}`;
}
function parseRuleTicket(ticket) {
    const m = /^rt\.(\d+)\.(.+)$/.exec(ticket);
    if (m === null)
        return undefined;
    return { index: Number(m[1]), recordId: m[2] };
}
export async function prepareCardApproval(opts) {
    const owner = resolveCallerOwner(opts.principal, opts.owner, "prepareCardApproval");
    if ("candidates" in opts) {
        const e = new Error("prepareCardApproval does not accept caller candidates — card options are minted by the engine from the adjudicated command");
        e.code = "config.invalid_argument";
        throw e;
    }
    const form = cardRuleFormOf(opts.toolName);
    if (form === undefined)
        return undefined;
    const oneRuleCard = form === "command" ? undefined : form;
    const scope = (() => {
        if (opts.scope !== undefined) {
            if (!isValidConsentScope(opts.scope)) {
                const e = new Error("prepareCardApproval got a scope that is not a consent-face scope (global, project with a non-empty root, or session with a non-empty sessionId) — refusing to guess where this consent should land");
                e.code = "config.invalid_argument";
                throw e;
            }
            return opts.scope;
        }
        if (opts.cwd !== undefined) {
            if (typeof opts.cwd !== "string" || opts.cwd === "") {
                const e = new Error("prepareCardApproval got a cwd that is not a usable path — it cannot anchor the derived project scope, and refusing beats minting a rule scoped to garbage");
                e.code = "config.invalid_argument";
                throw e;
            }
            return { kind: "project", root: opts.cwd };
        }
        const e = new Error("prepareCardApproval was given neither a scope nor a cwd — there is nowhere for this consent to land, and no direction of silence is honest (config.missing_scope): pass an explicit scope, or thread the adjudicated call's cwd");
        e.code = "config.missing_scope";
        throw e;
    })();
    let coverage;
    if (oneRuleCard === undefined) {
        try {
            const view = await effectiveOrThrow(storeForOwner(opts.deps.provider, owner), opts.sessionId !== undefined ? { sessionId: opts.sessionId } : undefined);
            const table = view.rules;
            coverage = segmentCoverageOf(opts.command, { persisted: table }, { tool: COMMAND_RULE_TOOL, cwd: opts.cwd, sessionId: opts.sessionId, ...(opts.execCwd !== undefined ? { execCwd: opts.execCwd } : {}) });
        }
        catch {
            coverage = undefined;
        }
    }
    const wholeToolOffer = () => insidePeerOfferOf(opts.deps.provider.a2aPeers, opts.toolName) ?? suggestRuleForTool(opts.toolName);
    const suggested = oneRuleCard !== undefined
        ? [oneRuleCard === "name" ? suggestRuleForName(opts.toolName, opts.command) : oneRuleCard === "domain" ? suggestRuleForHost(opts.toolName, opts.command) : opts.command === "" ? wholeToolOffer() : undefined].filter((o) => o !== undefined)
        : suggestRulesForCommand(opts.command, {
            ...(coverage !== undefined ? { coverage } : {}),
            scope,
            ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
            ...(opts.execCwd !== undefined ? { execCwd: opts.execCwd } : {}),
            ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}),
            ...(opts.deps.deniesDirectoryRead !== undefined ? { deniesDirectoryRead: opts.deps.deniesDirectoryRead } : {}),
        });
    const candidates = [];
    const claimedBy = new Map();
    const claim = (text, peerFingerprint) => {
        if (claimedBy.has(text))
            throw new Error(`engine defect: rule "${text}" was minted into two offers on one card`);
        const index = candidates.length;
        candidates.push({ behavior: "allow", rule: text, scope, ...(peerFingerprint !== undefined ? { peerFingerprint } : {}) });
        claimedBy.set(text, index);
        return index;
    };
    const offers = suggested.map((offer) => offer.kind === "single"
        ? { kind: "single", candidate: claim(offer.rule, offer.peerFingerprint) }
        : {
            kind: "batch",
            candidates: offer.rules.map((r) => claim(r.rule)),
            segments: offer.rules.map((r) => r.segment),
            uncoveredSegments: offer.uncoveredSegments,
            uncoveredDetail: offer.uncoveredDetail ?? [],
        });
    if (candidates.length === 0)
        return undefined;
    const record = {
        id: mintId(opts.deps, "rar"),
        ...recordIdentityOf(owner),
        schema: RULE_APPROVAL_RECORD_SCHEMA,
        kind: "card",
        state: "pending",
        rev: 0,
        candidates,
        offers,
        ...(oneRuleCard !== undefined ? {} : { command: opts.command }),
        createdAt: nowIso(opts.deps),
        ...(opts.toolCallId !== undefined ? { toolCallId: opts.toolCallId } : {}),
        ...(opts.boundInputHash !== undefined ? { boundInputHash: opts.boundInputHash } : {}),
    };
    const created = await storeStep(() => opts.deps.approvals.create(record), RECORD_CREATE);
    if ("refused" in created)
        return created.refused;
    return {
        approvalId: record.id,
        offers: ruleOffersOfRecord(record),
        tickets: candidates.map((_, i) => mintRuleTicket(record.id, i)),
        candidates,
    };
}
export async function redeemSessionReadRoot(opts) {
    const notWritten = (reason) => ({ landed: false, reason, committed: "no" });
    const scope = { kind: "session", sessionId: opts.sessionId };
    if (!isValidConsentScope(scope))
        return notWritten("the run has no session id a session rule could live under");
    const parsed = parseRuleText(formatRuleText(opts.dir, "subpath", READ_RULE_TOOL), "allow");
    if (!("rule" in parsed) || parsed.rule.tool !== READ_RULE_TOOL || parsed.rule.match !== "subpath" || parsed.rule.command !== opts.dir) {
        return notWritten(`the directory does not read back as one directory rule over itself${"reject" in parsed ? ` (${parsed.reject.message})` : ""}`);
    }
    let denied;
    try {
        denied = opts.deniesDirectoryRead(opts.dir) === true;
    }
    catch {
        denied = true;
    }
    if (denied)
        return notWritten("the deployment's read-deny rules name this directory");
    let owner;
    try {
        const now = opts.sessionRowOwner();
        if (now === undefined)
            return notWritten("the rule store's writer is not this engine's, and a session-long grant does not take it");
        owner = resolveCallerOwner(undefined, now, "redeemSessionReadRoot");
        const writer = writerOf(storeForOwner(opts.deps.provider, owner));
        if (writer === undefined)
            return notWritten("the resolved permission-rule store has no write face");
    }
    catch (err) {
        return notWritten(`the rule store's writer could not be obtained (${errText(err)})`);
    }
    const deps = { provider: opts.deps.provider, approvals: new InMemoryRuleApprovalRecordStore(), ...(opts.deps.now !== undefined ? { now: opts.deps.now } : {}), ...(opts.deps.newId !== undefined ? { newId: opts.deps.newId } : {}) };
    const record = {
        id: mintId(deps, "rar"),
        ...recordIdentityOf(owner),
        schema: RULE_APPROVAL_RECORD_SCHEMA,
        kind: "card",
        state: "pending",
        rev: 0,
        candidates: [{ behavior: "allow", rule: parsed.rule.rule, scope }],
        offers: [{ kind: "single", candidate: 0 }],
        createdAt: nowIso(deps),
        toolCallId: opts.toolCallId,
        ...(opts.boundInputHash !== undefined ? { boundInputHash: opts.boundInputHash } : {}),
    };
    const ended = "the call ended before the session rule was written";
    const cut = () => opts.signal?.aborted === true;
    if (cut())
        return notWritten(ended);
    const created = await storeStep(() => deps.approvals.create(record), RECORD_CREATE);
    if ("refused" in created)
        return notWritten(created.refused.reason);
    const who = owner.kind === "principal" ? { principal: owner.principal } : { owner };
    const confirmed = await confirmRuleApproval({ approvalId: record.id, ...who, selectedOffer: 0, deps });
    if (!confirmed.ok)
        return notWritten(`the consent record refused the confirmation${confirmed.detail !== undefined ? ` (${confirmed.detail.message})` : ""}`);
    if (cut())
        return notWritten(ended);
    const redeemed = await redeemRuleTicket({ ticket: mintRuleTicket(record.id, 0), ...who, deps });
    return redeemed.status === "redeemed" ? { landed: true, rule: redeemed.rule } : { landed: false, reason: redeemed.reason, committed: redeemed.committed };
}
export async function confirmRuleApproval(opts) {
    const caller = resolveCallerOwner(opts.principal, opts.owner, "confirmRuleApproval");
    const no = (reason, detail) => ({
        ok: false,
        reason,
        ...(detail !== undefined ? { detail } : {}),
    });
    if (opts.editedCandidate !== undefined && opts.selectedOffer !== undefined) {
        const e = new Error("confirmRuleApproval takes selectedOffer OR editedCandidate, never both — one confirmation carries one choice");
        e.code = "config.invalid_argument";
        throw e;
    }
    if ("selectedCandidate" in opts) {
        const e = new Error("confirmRuleApproval no longer takes selectedCandidate — selection is by OFFER index (selectedOffer) against the prepared record's offers; re-fetch the card and choose an offer");
        e.code = "config.invalid_argument";
        throw e;
    }
    const read = await storeStep(() => opts.deps.approvals.get(opts.approvalId), RECORD_READ);
    if ("refused" in read)
        return confirmStoreFailure(read.refused);
    const rec = read.value;
    const recOwner = rec === undefined ? undefined : ownerOfRecord(rec);
    if (rec === undefined || recOwner === undefined || !sameRuleOwner(recOwner, caller))
        return no("record_not_found");
    if (isStale(rec))
        return no("record_schema_stale", { message: STALE_RECORD_MESSAGE });
    const damage = approvalRecordDamageOf(rec);
    if (damage !== undefined)
        return no("record_malformed", { message: damage });
    if (opts.editedCandidate !== undefined)
        return await confirmEditedCandidate(rec, opts.editedCandidate, opts.deps);
    const chosen = opts.selectedOffer === undefined ? (rec.offers.length === 1 ? 0 : undefined) : opts.selectedOffer;
    if (chosen === undefined)
        return no("selection_missing");
    if (!Number.isInteger(chosen) || rec.offers[chosen] === undefined)
        return no("selection_invalid");
    if (rec.state === "approved" || rec.state === "redeemed") {
        const stored = rec.selectedOffer;
        if (stored === undefined || !Number.isInteger(stored) || rec.offers[stored] === undefined) {
            return no("record_malformed", { message: "the settled record does not name a valid chosen offer" });
        }
        return stored === chosen ? { ok: true } : no("selection_mismatch");
    }
    if (rec.state !== "pending")
        return no("not_pending");
    if (rec.selectedOffer !== undefined)
        return no("record_malformed", { message: "a pending record must not already carry a chosen offer" });
    const casted = await storeStep(() => opts.deps.approvals.cas(rec.id, rec.rev, { ...rec, rev: rec.rev + 1, state: "approved", selectedOffer: chosen }), RECORD_CONFIRM_CAS);
    if ("refused" in casted)
        return confirmStoreFailure(casted.refused);
    if (casted.value)
        return { ok: true };
    const reread = await storeStep(() => opts.deps.approvals.get(rec.id), RECORD_READ);
    if ("refused" in reread)
        return confirmStoreFailure(reread.refused);
    const again = reread.value;
    if (again === undefined)
        return no("record_not_found");
    if (isStale(again))
        return no("record_schema_stale", { message: STALE_RECORD_MESSAGE });
    if (again.state === "pending")
        return no("conflict");
    const settled = again.selectedOffer;
    if (settled === undefined || !Number.isInteger(settled) || again.offers[settled] === undefined) {
        return no("record_malformed", { message: "the settled record does not name a valid chosen offer" });
    }
    return settled === chosen ? { ok: true } : no("selection_mismatch");
}
function normalizeEditedSpelling(text) {
    const m = /^([A-Za-z][A-Za-z0-9_]*)\((.+)\)$/.exec(text);
    if (m === null)
        return text;
    const head = m[1];
    const content = m[2];
    if (head === undefined || content === undefined)
        return text;
    const read = head === COMMAND_RULE_TOOL ? foldSpacing(content) : content;
    if (read === undefined)
        return text;
    const body = /^(.+) \*$/.exec(read)?.[1];
    if (body === undefined || body.includes("*"))
        return text;
    return `${head}(${body}:*)`;
}
function parseSubmittedSpelling(text) {
    return parseRuleText(normalizeEditedSpelling(text), "allow");
}
function checkEditedRuleText(text, command) {
    const parsed = parseSubmittedSpelling(text);
    if ("reject" in parsed)
        return { ok: false, code: parsed.reject.code, message: parsed.reject.message };
    if (parsed.rule.match === "tool") {
        return { ok: false, message: `the edited rule "${parsed.rule.rule}" names the whole tool — a card's edit names a command rule, and a standing yes to every command is not one a card mints` };
    }
    if (!ruleAdmitsCommand(parsed.rule, command)) {
        return {
            ok: false,
            message: `the edited rule "${parsed.rule.rule}" does not admit the command that was decided ("${escapeForDisclosure(command)}") — a card's edit may widen how much the rule covers, never move it to a different grant`,
        };
    }
    const warnings = ruleBreadthWarningsOf(parsed.rule);
    return { ok: true, canonicalRule: parsed.rule.rule, ...(warnings.length > 0 ? { warnings } : {}) };
}
export function precheckEditedRuleText(text, command) {
    if (typeof text !== "string") {
        const e = new Error(`precheckEditedRuleText takes the edited rule text as a string (got ${typeof text}) — a non-string is a caller bug, not a rule a person could have typed`);
        e.code = "config.invalid_argument";
        throw e;
    }
    if (typeof command !== "string" || command === "") {
        const e = new Error("precheckEditedRuleText takes the adjudicated command the card was drawn for — coverage cannot be judged without it, and reporting the absence as a rejected rule would blame the person's text");
        e.code = "config.invalid_argument";
        throw e;
    }
    if (hasUnrenderableCharacters(command)) {
        const e = new Error("precheckEditedRuleText takes a command this lane can read — one carrying control or format characters is refused at this preflight face (likelier a caller wiring fault than a card's command; the in-engine confirmation arm still judges such a card, with the command escaped on its refusal line)");
        e.code = "config.invalid_argument";
        throw e;
    }
    return checkEditedRuleText(text, command);
}
async function confirmEditedCandidate(rec, edit, deps) {
    const no = (reason, detail) => ({
        ok: false,
        reason,
        ...(detail !== undefined ? { detail } : {}),
    });
    if (rec.kind !== "card") {
        return no("edit_rejected", { message: "a batch record takes no edited candidate — its confirmation covers the previewed list whole" });
    }
    if (typeof edit.boundInputHash !== "string" || edit.boundInputHash === "")
        return no("edit_binding_mismatch");
    if (rec.boundInputHash === undefined) {
        return no("edit_binding_mismatch");
    }
    if (edit.boundInputHash !== rec.boundInputHash)
        return no("edit_binding_mismatch");
    if (rec.state === "approved" || rec.state === "redeemed") {
        if (rec.edited === undefined)
            return no("selection_mismatch");
        const canonical = rec.candidates[rec.edited.index]?.rule;
        if (canonical === undefined)
            return no("selection_mismatch");
        let hit = edit.text === rec.edited.text;
        if (!hit) {
            const reparsed = parseSubmittedSpelling(edit.text);
            hit = "rule" in reparsed && reparsed.rule.rule === canonical;
        }
        if (!hit)
            return no("selection_mismatch");
        return { ok: true, mintedCandidate: { index: rec.edited.index, rule: canonical, ticket: mintRuleTicket(rec.id, rec.edited.index) } };
    }
    if (rec.state !== "pending")
        return no("not_pending");
    if (deps.cardEdits !== undefined && typeof deps.cardEdits !== "boolean") {
        throw new Error(`RuleConsentDeps.cardEdits must be a boolean when present (got ${typeof deps.cardEdits}) — refusing to guess whether the card-edit face is enabled`);
    }
    if (deps.cardEdits !== true)
        return no("edit_disabled");
    const scope = rec.candidates[0]?.scope;
    if (scope === undefined || !rec.candidates.every((c) => sameScope(c.scope, scope))) {
        return no("edit_rejected", { message: "the record's candidates carry no single common scope — an edited candidate inherits the card's scope, and a record without one is malformed" });
    }
    if (rec.command === undefined) {
        return no("edit_rejected", { message: "the record does not carry an adjudicated command (a name card, or one minted before card edits existed) — coverage cannot be verified, so the edit is refused" });
    }
    const checked = checkEditedRuleText(edit.text, rec.command);
    if (!checked.ok) {
        return no("edit_rejected", { ...(checked.code !== undefined ? { code: checked.code } : {}), message: checked.message });
    }
    const index = rec.candidates.length;
    const next = {
        ...rec,
        rev: rec.rev + 1,
        state: "approved",
        candidates: [...rec.candidates, { behavior: "allow", rule: checked.canonicalRule, scope }],
        offers: [...rec.offers, { kind: "single", candidate: index }],
        selectedOffer: rec.offers.length,
        edited: { index, text: edit.text, at: nowIso(deps), ...(checked.warnings !== undefined ? { warnings: checked.warnings.map((w) => w.code) } : {}) },
    };
    const casted = await storeStep(() => deps.approvals.cas(rec.id, rec.rev, next), RECORD_EDIT_CAS);
    if ("refused" in casted)
        return confirmStoreFailure(casted.refused);
    if (!casted.value) {
        const reread = await storeStep(() => deps.approvals.get(rec.id), RECORD_READ);
        if ("refused" in reread)
            return confirmStoreFailure(reread.refused);
        const again = reread.value;
        if (again === undefined || isStale(again))
            return no("record_not_found");
        if (again.state === "pending")
            return no("conflict");
        return await confirmEditedCandidate(again, edit, deps);
    }
    return { ok: true, mintedCandidate: { index, rule: checked.canonicalRule, ticket: mintRuleTicket(rec.id, index) } };
}
function refusalRetriable(code, committed) {
    return (code === "store_read" || code === "store_write") && committed === "no";
}
function refusal(code, reason, committed = "no") {
    return { status: "refused", code, committed, retriable: refusalRetriable(code, committed), reason };
}
async function storeStep(step, failure) {
    try {
        const value = await step();
        const answers = failure.answers;
        if (answers !== undefined && !answers.accepts(value)) {
            return { refused: refusal(failure.code, `${failure.what}: the store answered ${answerKindOf(value)}, not ${answers.expected}`) };
        }
        return { value };
    }
    catch (err) {
        return { refused: refusal(failure.code, `${failure.what}: ${errText(err)}`) };
    }
}
function answerKindOf(answer) {
    return answer === null ? "null" : Array.isArray(answer) ? "a list" : typeof answer === "object" ? "an object" : `a ${typeof answer}`;
}
const RECORD_ANSWER = { accepts: (a) => a === undefined || (typeof a === "object" && a !== null && !Array.isArray(a)), expected: "a record, a stale-record envelope or nothing" };
const CAS_ANSWER = { accepts: (a) => typeof a === "boolean", expected: "a boolean" };
const RECORD_READ = { code: "store_read", what: "could not read the approval record", answers: RECORD_ANSWER };
const RECORD_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this redemption's dot", answers: CAS_ANSWER };
const DOT_ALLOCATION = { code: "store_write", what: "the permission-rule store failed to allocate this redemption's dot" };
const RECORD_CREATE = { code: "store_write", what: "the approval record store failed to create the record" };
const RECORD_CONFIRM_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this confirmation", answers: CAS_ANSWER };
const RECORD_EDIT_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this card edit", answers: CAS_ANSWER };
function confirmStoreFailure(refused) {
    return { ok: false, reason: refused.code, detail: { message: refused.reason } };
}
export async function redeemRuleTicket(opts) {
    const caller = resolveCallerOwner(opts.principal, opts.owner, "redeemRuleTicket");
    const parsed = parseRuleTicket(opts.ticket);
    if (parsed === undefined)
        return refusal("ticket_invalid", "malformed ticket");
    const read = await storeStep(() => opts.deps.approvals.get(parsed.recordId), RECORD_READ);
    if ("refused" in read)
        return read.refused;
    const rec = read.value;
    if (rec === undefined)
        return refusal("record_missing", "no such approval record");
    const recOwner = ownerOfRecord(rec);
    if (recOwner === undefined || !sameRuleOwner(recOwner, caller))
        return refusal("wrong_principal", "the ticket belongs to a different principal");
    if (isStale(rec))
        return refusal("record_schema_stale", `record_schema_stale: ${STALE_RECORD_MESSAGE}`);
    if (rec.state === "pending")
        return refusal("not_confirmed", "the approval record has not been confirmed");
    const damage = approvalRecordDamageOf(rec);
    if (damage !== undefined)
        return refusal("record_malformed", `the approval record is malformed: ${damage}`);
    const candidate = rec.candidates[parsed.index];
    if (candidate === undefined)
        return refusal("ticket_invalid", "the ticket names no candidate on this record");
    const chosen = rec.selectedOffer;
    const chosenOffer = chosen !== undefined && Number.isInteger(chosen) ? rec.offers[chosen] : undefined;
    if (chosenOffer === undefined) {
        return refusal("record_malformed", "the approval record is malformed: it is settled but names no valid chosen offer");
    }
    if (!offerMembersOf(chosenOffer).includes(parsed.index)) {
        return refusal("not_chosen", "the ticket names an option the person did not choose");
    }
    const siblingsOf = candidate.behavior === "allow" ? { rec, offer: chosenOffer, index: parsed.index } : undefined;
    const bound = boundStampOf(rec, chosenOffer, parsed.index);
    const stamp = "stamp" in bound ? bound.stamp : undefined;
    const parsedRule = parseRuleText(candidate.rule, candidate.behavior);
    if ("reject" in parsedRule)
        return refusal("parse_rejected", `${parsedRule.reject.code}: ${parsedRule.reject.message}`);
    if (rec.kind === "import" && !importCarries(candidate.scope, parsedRule.rule))
        return refusal("unsupported.layer_root", LAYER_ROOT_RECORD_REASON);
    let store;
    try {
        store = storeForOwner(opts.deps.provider, caller);
    }
    catch (err) {
        return refusal("store_unavailable", errText(err));
    }
    const writer = writerOf(store);
    if (writer === undefined)
        return refusal("store_unavailable", "the resolved permission-rule store has no write face");
    const known = rec.redeemedDots?.[parsed.index];
    let dot;
    if (known !== undefined) {
        dot = known;
    }
    else {
        const minted = await storeStep(() => writer.nextDot(), DOT_ALLOCATION);
        if ("refused" in minted)
            return minted.refused;
        dot = minted.value;
    }
    if (known === undefined) {
        const next = {
            ...rec,
            rev: rec.rev + 1,
            state: "redeemed",
            redeemedDots: { ...(rec.redeemedDots ?? {}), [parsed.index]: dot },
        };
        const casted = await storeStep(() => opts.deps.approvals.cas(rec.id, rec.rev, next), RECORD_CAS);
        if ("refused" in casted)
            return casted.refused;
        if (!casted.value) {
            const reread = await storeStep(() => opts.deps.approvals.get(rec.id), RECORD_READ);
            if ("refused" in reread)
                return reread.refused;
            const again = reread.value;
            const theirs = again === undefined || isStale(again) ? undefined : again.redeemedDots?.[parsed.index];
            if (theirs === undefined)
                return refusal("record_changed", "the approval record changed state concurrently");
            return await applyRedemption({ deps: opts.deps, owner: caller, candidate, ...(stamp !== undefined ? { stamp } : {}), parsedRule: parsedRule.rule, dot: theirs, recordId: rec.id, kind: rec.kind, replay: true, ...(siblingsOf !== undefined ? { siblingsOf } : {}) });
        }
    }
    return await applyRedemption({ deps: opts.deps, owner: caller, candidate, ...(stamp !== undefined ? { stamp } : {}), parsedRule: parsedRule.rule, dot, recordId: rec.id, kind: rec.kind, replay: known !== undefined, ...(siblingsOf !== undefined ? { siblingsOf } : {}) });
}
async function tighteningSiblingsStand(rec, offer, index, store, durableSnapshot) {
    for (const member of offerMembersOf(offer)) {
        if (member === index)
            continue;
        const sibling = rec.candidates[member];
        if (sibling === undefined || sibling.behavior === "allow")
            continue;
        const dot = rec.redeemedDots?.[member];
        if (dot === undefined)
            return false;
        const view = sibling.scope.kind === "session" ? await effectiveOrThrow(store, { sessionId: sibling.scope.sessionId }) : durableSnapshot;
        if (!redeemedDotLive(view, sibling, dot))
            return false;
    }
    return true;
}
function redeemedDotLive(view, candidate, dot) {
    return view.rules.some((r) => r.behavior === candidate.behavior && sameScope(r.scope, candidate.scope) && r.adds.some((a) => a.dot.actor === dot.actor && a.dot.counter === dot.counter));
}
async function applyRedemption(args) {
    let store;
    try {
        store = storeForOwner(args.deps.provider, args.owner);
    }
    catch (err) {
        return refusal("store_unavailable", errText(err));
    }
    const writer = writerOf(store);
    if (writer === undefined)
        return refusal("store_unavailable", "the resolved permission-rule store has no write face");
    const origin = originOfRecordKind(args.kind);
    const siblings = args.siblingsOf;
    const landing = await landRuleAdd({
        store,
        writer,
        delta: {
            kind: "redemption-add",
            behavior: args.parsedRule.behavior,
            rule: args.parsedRule.rule,
            scope: args.candidate.scope,
            tool: args.parsedRule.tool,
            match: args.parsedRule.match,
            command: args.parsedRule.command,
            add: { dot: args.dot, origin, createdAt: nowIso(args.deps), ...(args.stamp !== undefined ? { peerFingerprint: args.stamp } : {}) },
            redemption: {
                recordId: args.recordId,
                ...(args.owner.kind === "principal" ? { principal: args.owner.principal } : { owner: args.owner }),
            },
        },
        ...(siblings !== undefined
            ? {
                preflight: async (snapshot) => (await tighteningSiblingsStand(siblings.rec, siblings.offer, siblings.index, store, snapshot))
                    ? undefined
                    : "withheld: this allow belongs to a batch whose deny/ask members do not all stand in the store — an allow must not stand wider than the list that was confirmed; redeem the batch (redeemRuleBatch) so the tightening members land first, or draw a fresh card",
            }
            : {}),
    });
    if (!landing.landed)
        return refusal(landing.code, landing.reason, landing.committed);
    let live = false;
    let snap;
    try {
        snap = await effectiveOrThrow(store, args.candidate.scope.kind === "session" ? { sessionId: args.candidate.scope.sessionId } : undefined);
        live = redeemedDotLive(snap, args.candidate, args.dot);
    }
    catch (err) {
        return refusal("store_read", `could not read the permission-rule store to confirm this ${args.candidate.behavior} rule stands after its redemption: ${errText(err)}`, "unknown");
    }
    if (!live) {
        const left = snap?.droppedRows?.find((d) => d.rule === args.parsedRule.rule);
        const unread = left === undefined ? snap?.unreadableRows?.find((u) => u.rule === args.parsedRule.rule && (u.behavior === args.candidate.behavior || u.member === "behavior")) : undefined;
        return refusal("dot_removed", left !== undefined
            ? `this ${args.candidate.behavior} rule was stored (dot ${args.dot.actor}#${args.dot.counter}), and the store's read leaves the stored row out (${left.reason}) — it takes no part in any check, and a new consent would store it the same way`
            : unread !== undefined
                ? `this ${args.candidate.behavior} rule was stored (dot ${args.dot.actor}#${args.dot.counter}), and the store's read cannot read the stored row back as data (its ${unread.member}: ${unread.reason}) — ${unread.reach === "as_read" ? `it applies as written${unread.member === "scope" ? " (everywhere: its scope is the part that could not be read)" : ""}, but this add of it cannot be named` : "it stands at its strictest reading (no allow rule clears a call it may reach)"} until the store serves its members as plain values`
                : `this ${args.candidate.behavior} rule's redeemed dot ${args.dot.actor}#${args.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required`);
    }
    return { status: "redeemed", behavior: args.parsedRule.behavior, rule: args.parsedRule.rule, scope: args.candidate.scope, dot: args.dot, rev: landing.rev, alreadyRedeemed: args.replay };
}
function originOfRecordKind(kind) {
    return kind === "import" ? "imported-cc" : kind === "starter" ? "starter" : "user";
}
export const IMPORTED_SETTINGS_LAYERS = Object.freeze(["userSettings", "projectSettings", "localSettings"]);
const IMPORT_UNCOVERED_LAYERS = { flagSettings: "not-imported-v1", policySettings: "not-imported-v1" };
function importCarries(scope, rule) {
    return !(scope.kind === "global" && ruleBasesNeeded(rule).includes("root"));
}
const LAYER_ROOT_SKIP_REASON = "unsupported.layer_root: a path pattern written from `/` in the user settings layer reads at that layer's own directory (the configuration directory), and a stored global rule reads `/` at the project root of each task — the stored copy would guard or open another directory, so it stays in the settings file, unimported; to carry it, spell the directory out (`//<directory>/…`, or `~/<path>` under the home) — a directory whose name holds `*`, `?`, `[`, `]`, `{` or `}` has no literal spelling in the path grammar and cannot be written this way";
const LAYER_ROOT_RECORD_REASON = "unsupported.layer_root: this import record carries a global rule written from `/` — the user settings layer reads it at its own directory (the configuration directory), a stored global rule reads it at the project root of each task, so it does not land; prepare the import again and the entry is disclosed in skipped, left in the settings file";
export async function prepareCcImport(opts) {
    const owner = resolveCallerOwner(opts.principal, opts.owner, "prepareCcImport");
    opts.layers.forEach((layer, i) => {
        if (layer.layer === "userSettings" && layer.root !== undefined) {
            const field = `layers[${i}].root`;
            const e = new Error(`prepareCcImport got a root on the user settings layer (${field}) — the user layer has no root: its rules import as global rules, which read \`/\` at each task's project root, and nothing reads that layer's own directory; drop the member (a project or local layer keeps its root)`);
            e.code = "config.invalid_argument";
            e.detail = { field };
            throw e;
        }
    });
    const candidates = [];
    const skipped = [];
    const layers = [];
    for (const layer of opts.layers) {
        let raw;
        try {
            raw = await layer.readFile(layer.path);
        }
        catch {
            raw = undefined;
        }
        if (raw === undefined) {
            layers.push({ path: layer.path, layer: layer.layer, found: false });
            continue;
        }
        layers.push({ path: layer.path, layer: layer.layer, found: true });
        let settingsRoot;
        try {
            settingsRoot = JSON.parse(raw);
        }
        catch (err) {
            skipped.push({ rule: layer.path, reason: `settings file is not valid JSON (${errText(err)})` });
            continue;
        }
        let container;
        if (settingsRoot === null)
            container = undefined;
        else if (typeof settingsRoot === "object" && !Array.isArray(settingsRoot))
            container = settingsRoot.permissions;
        else {
            skipped.push({
                rule: layer.path,
                reason: `settings file is not a JSON object — no bucket in this layer could be read, so it is reported as unread rather than as empty (it stays in the settings file either way)`,
            });
            continue;
        }
        let permissions;
        if (container === undefined || container === null)
            permissions = undefined;
        else if (typeof container === "object" && !Array.isArray(container))
            permissions = container;
        else {
            skipped.push({
                rule: layer.path,
                reason: `settings "permissions" is not an object — no bucket in this layer could be read, so it is reported as unread rather than as empty (it stays in the settings file either way)`,
            });
            continue;
        }
        const scope = layer.layer === "userSettings" ? { kind: "global" } : { kind: "project", root: layer.root };
        for (const behavior of RULE_BEHAVIORS) {
            const entries = permissions?.[behavior];
            if (entries === undefined || entries === null)
                continue;
            if (!Array.isArray(entries)) {
                skipped.push({
                    rule: layer.path,
                    reason: `settings ${behavior} bucket is not an array — no entry in it could be read (it stays in the settings file either way)`,
                });
                continue;
            }
            for (const entry of entries) {
                if (typeof entry !== "string") {
                    skipped.push({ rule: String(entry), reason: `settings ${behavior} entry is not a string` });
                    continue;
                }
                const parsed = parseRuleText(entry, behavior);
                if ("reject" in parsed) {
                    skipped.push({ rule: entry, reason: `${parsed.reject.code}: ${parsed.reject.message}` });
                    continue;
                }
                if (parsed.rule.match === "tool") {
                    skipped.push({ rule: entry, reason: "unsupported.form: a bare tool-name entry is a name-set item the host carries from the settings layer's own lists — it stays in the settings file, unimported" });
                    continue;
                }
                if (!importCarries(scope, parsed.rule)) {
                    skipped.push({ rule: entry, reason: LAYER_ROOT_SKIP_REASON });
                    continue;
                }
                if (candidates.some((c) => c.behavior === behavior && c.rule === parsed.rule.rule && sameScope(c.scope, scope)))
                    continue;
                candidates.push({ behavior, rule: parsed.rule.rule, scope });
            }
        }
    }
    const preview = { candidates, skipped, layers, uncovered: { ...IMPORT_UNCOVERED_LAYERS } };
    if (candidates.length === 0)
        return { preview };
    const record = {
        id: mintId(opts.deps, "rar"),
        ...recordIdentityOf(owner),
        schema: RULE_APPROVAL_RECORD_SCHEMA,
        kind: "import",
        state: "pending",
        rev: 0,
        candidates,
        offers: [{ kind: "batch", candidates: candidates.map((_, i) => i) }],
        createdAt: nowIso(opts.deps),
    };
    const created = await storeStep(() => opts.deps.approvals.create(record), RECORD_CREATE);
    if ("refused" in created)
        return created.refused;
    return { preview, approvalId: record.id };
}
export const STARTER_RULES = [
    "Bash(ls)",
    "Bash(ls -la)",
    "Bash(pwd)",
    "Bash(whoami)",
    "Bash(uname -a)",
    "Bash(date)",
    "Bash(df -h)",
    "Bash(node --version)",
    "Bash(npm --version)",
];
export async function prepareStarterBatch(opts) {
    const owner = resolveCallerOwner(opts.principal, opts.owner, "prepareStarterBatch");
    const candidates = [];
    for (const text of STARTER_RULES) {
        const parsed = parseRuleText(text, "allow");
        if ("reject" in parsed)
            throw new Error(`starter rule "${text}" is not a valid rule: ${parsed.reject.message}`);
        candidates.push({ behavior: "allow", rule: parsed.rule.rule, scope: { kind: "global" } });
    }
    const record = {
        id: mintId(opts.deps, "rar"),
        ...recordIdentityOf(owner),
        schema: RULE_APPROVAL_RECORD_SCHEMA,
        kind: "starter",
        state: "pending",
        rev: 0,
        candidates,
        offers: [{ kind: "batch", candidates: candidates.map((_, i) => i) }],
        createdAt: nowIso(opts.deps),
    };
    const created = await storeStep(() => opts.deps.approvals.create(record), RECORD_CREATE);
    if ("refused" in created)
        return created.refused;
    return { preview: candidates, approvalId: record.id };
}
export async function redeemRuleBatch(opts) {
    const caller = resolveCallerOwner(opts.principal, opts.owner, "redeemRuleBatch");
    const read = await storeStep(() => opts.deps.approvals.get(opts.approvalId), RECORD_READ);
    if ("refused" in read)
        return read.refused;
    const rec = read.value;
    if (rec === undefined)
        return refusal("record_missing", "no such approval record");
    const recOwner = ownerOfRecord(rec);
    if (recOwner === undefined || !sameRuleOwner(recOwner, caller))
        return refusal("wrong_principal", "the record belongs to a different principal");
    if (isStale(rec))
        return refusal("record_schema_stale", `record_schema_stale: ${STALE_RECORD_MESSAGE}`);
    if (rec.state === "pending")
        return refusal("not_confirmed", "the approval record has not been confirmed");
    const damage = approvalRecordDamageOf(rec);
    if (damage !== undefined)
        return refusal("record_malformed", `the approval record is malformed: ${damage}`);
    const chosen = rec.selectedOffer;
    const chosenOffer = chosen !== undefined && Number.isInteger(chosen) ? rec.offers[chosen] : undefined;
    if (chosenOffer === undefined) {
        return refusal("record_malformed", "the approval record is malformed: it is settled but names no valid chosen offer");
    }
    let store;
    try {
        store = storeForOwner(opts.deps.provider, caller);
    }
    catch (err) {
        return refusal("store_unavailable", errText(err));
    }
    const members = [];
    let rev = 0;
    const ordered = [...offerMembersOf(chosenOffer)].sort((a, b) => {
        const ra = RULE_BEHAVIOR_PRECEDENCE[rec.candidates[a].behavior];
        const rb = RULE_BEHAVIOR_PRECEDENCE[rec.candidates[b].behavior];
        return ra !== rb ? ra - rb : a - b;
    });
    let tighteningFailed;
    for (const candidateIndex of ordered) {
        const candidate = rec.candidates[candidateIndex];
        const row = { candidateIndex, behavior: candidate.behavior, rule: candidate.rule, scope: candidate.scope };
        const tightening = candidate.behavior !== "allow";
        if (!tightening && tighteningFailed !== undefined) {
            members.push({ ...row, ...refusal("withheld", `withheld: candidate ${tighteningFailed} (a deny/ask member of this batch) did not land, and an allow must not stand wider than the list that was confirmed — redeem the batch again once the store accepts the tightening member`) });
            continue;
        }
        let alreadyThere = false;
        {
            try {
                const snap = await effectiveOrThrow(store, candidate.scope.kind === "session" ? { sessionId: candidate.scope.sessionId } : undefined);
                rev = snap.rev;
                alreadyThere = snap.rules.some((r) => r.behavior === candidate.behavior && r.rule === candidate.rule && sameScope(r.scope, candidate.scope));
            }
            catch (err) {
                members.push({ ...row, ...refusal("store_read", `could not read the permission-rule store: ${errText(err)}`) });
                if (tightening)
                    tighteningFailed ??= candidateIndex;
                continue;
            }
        }
        const res = await redeemRuleTicket({
            ticket: mintRuleTicket(rec.id, candidateIndex),
            ...(caller.kind === "principal" ? { principal: caller.principal } : { owner: caller }),
            deps: opts.deps,
        });
        if (res.status === "refused") {
            members.push({ ...row, ...res });
            if (tightening)
                tighteningFailed ??= candidateIndex;
            continue;
        }
        rev = candidate.scope.kind === "session" ? Math.max(rev, res.rev) : res.rev;
        members.push({ ...row, status: alreadyThere ? "deduped" : "persisted", alreadyRedeemed: res.alreadyRedeemed, dot: res.dot });
    }
    return { members, rev };
}