UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,082 lines • 61.6 kB
import { ABSOLUTE_HOST_PATH_MAX, isAbsoluteHostPath } from "@sema-agent/primitives";
import { userAttachmentOf } from "../../internal/llm.js";
import { normalizeFileText } from "../../tools/fs/encoding.js";
import { countLines, retireRead, witnessesAfterDelivery } from "../../tools/fs/fs-shared.js";
import { expandHomeTilde, isAbsoluteForFamily, lexicalViewOf, pathFamilyOf, sha256, startsWithDriveLetter, withinAnyRoot } from "../../tools/fs/safety.js";
import { relativeUnderRoot } from "../sensitive-path-policy.js";
import { ORG_ADJUDICATION_TIMEOUT_MS } from "../permission-rule-org.js";
import { instructionFrameOwnerOf, isInstructionLaneEntry, mintInstructionFrames } from "../user-attachment.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { agentIdOf } from "../leg-identity.js";
import { describeRejectedValue } from "../tool-search-setting.js";
import { strayMembersOf } from "../own-property-receipt.js";
import { RETIRED_INSTRUCTION_FAMILY_KEYS, retiredKeyOf, retiredKeyRefusal } from "../retired-keys.js";
import { appendAdmittedRow } from "../row-admission.js";
import { asThrownError, thrownText } from "../thrown-value.js";
import { announceDigest, withAnnounceDigests } from "./announce-once-ledger.js";
import { steeringPreview } from "./steering-preview.js";
import { cutInstructionText, INSTRUCTION_FILE_MAX_BYTES, INSTRUCTION_INCLUDE_MAX_DEPTH, instructionFileCap, isTextIncludeTarget, processInstructionText, ruleGlobsMatch } from "./nested-memory-content.js";
export const NESTED_MEMORY_MAX_NAMES = 8;
export const NESTED_MEMORY_NAME_MAX = 255;
export const NESTED_MEMORY_MAX_HOST_RULES = 20;
export const NESTED_MEMORY_MAX_APPROVED_PATHS = 32;
export const HOST_TEXT_LEVELS = Object.freeze(["user", "managed", "project", "local"]);
const OWNER_OF_LEVEL = { user: "deployment", managed: "deployment", project: "repository", local: "local" };
export const NESTED_MEMORY_PROBES_PER_LOAD = 32;
export const NESTED_MEMORY_FRAME_BUDGET_FILES = 3;
export const NESTED_MEMORY_STAT_BATCH = 8;
export const NESTED_MEMORY_PROBE_FACE = "nested-memory";
export const INSTRUCTIONS_WITHHELD = "instructions.withheld";
export const INSTRUCTIONS_WITHHELD_REASONS = Object.freeze(["rule_denied", "outside_roots", "approval_required", "admission_unknown", "target_moved", "outside_its_root", "too_many_texts", "unanchored"]);
export const INSTRUCTIONS_OUTSIDE_ROOT = "instructions.outside_root";
const INSTRUCTIONS_TRUNCATED = "instructions.truncated";
export const INSTRUCTIONS_FAMILY_UNDECLARED = "instructions.family_undeclared";
export function instructionsFamilyUndeclaredNotice(sessionId) {
    return {
        code: INSTRUCTIONS_FAMILY_UNDECLARED,
        message: "No instruction family is declared for this deployment's runs (`TaskSpec.instructionFamily` is absent), so no run reads any instruction file (CLAUDE.md or another) into the model's context. " +
            "To have them read, declare the family on the task spec: `instructionFamily: { files: [...] }` names the files each directory is read for (`rulesDirs`, `alternate`, `localFiles`, `includes`, `additionalDirectories`, `externalIncludes` and `hostRules` — the host's texts, each `{ level, name, text, rule? }` — are its other members). " +
            "Said once to each notice receiver (once per process with none wired); `projectMemory: \"disabled\"` on a request is the off switch that says it on purpose.",
        detail: { sessionId },
    };
}
const FIELD = "TaskSpec.instructionFamily";
export const NESTED_MEMORY_LANE = Object.freeze({
    declaration: FIELD,
    origin: "nested_memory",
    rootOrigin: "project_instructions",
    echo: "steering_injected",
    notice: INSTRUCTIONS_WITHHELD,
    limits: Object.freeze({ maxNames: NESTED_MEMORY_MAX_NAMES, maxNameChars: NESTED_MEMORY_NAME_MAX, maxHostRules: NESTED_MEMORY_MAX_HOST_RULES, maxApprovedPaths: NESTED_MEMORY_MAX_APPROVED_PATHS, maxApprovedPathChars: ABSOLUTE_HOST_PATH_MAX, maxIncludeDepth: INSTRUCTION_INCLUDE_MAX_DEPTH, probesPerLoad: NESTED_MEMORY_PROBES_PER_LOAD }),
});
const refuse = (at, problem) => Object.assign(new Error(`${at}: ${problem}`), { code: "config.invalid_argument" });
const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
function onlyKeys(v, keys, at) {
    const stray = strayMembersOf(v, { subject: at, unit: "member", moment: "when the run is prepared" }, keys);
    if (stray !== undefined)
        throw Object.assign(new Error(stray.sentence), { code: "config.invalid_argument" });
}
function screenName(v, at) {
    if (typeof v !== "string")
        throw refuse(at, `must be a string (got ${describeRejectedValue(v)}).`);
    if (v.length === 0)
        throw refuse(at, "is empty.");
    if (v.length > NESTED_MEMORY_NAME_MAX)
        throw refuse(at, `is ${v.length} characters, over ${NESTED_MEMORY_NAME_MAX}.`);
    if (v.includes("\u0000"))
        throw refuse(at, "holds a NUL character.");
    if (v.includes("\\") || startsWithDriveLetter(v))
        throw refuse(at, "must be a `/`-separated relative name (no backslash, no drive letter): the engine joins it to each directory itself.");
    if (v.startsWith("/"))
        throw refuse(at, "is absolute — it must be relative to each directory it is read in.");
    const segments = v.split("/");
    if (segments.some((s) => s === ""))
        throw refuse(at, "has an empty segment (a doubled or trailing `/`).");
    if (segments.some((s) => s === "." || s === ".."))
        throw refuse(at, "has a `.` or `..` segment — a name stays inside the directory it is read in.");
    return v;
}
function screenNames(v, at, seen) {
    if (!Array.isArray(v))
        throw refuse(at, `must be an array of names (got ${describeRejectedValue(v)}).`);
    if (v.length === 0)
        throw refuse(at, "is empty — omit it instead.");
    if (v.length > NESTED_MEMORY_MAX_NAMES)
        throw refuse(at, `has ${v.length} names, over ${NESTED_MEMORY_MAX_NAMES}.`);
    return Array.from(v).map((x, i) => {
        const name = screenName(x, `${at}[${i}]`);
        const fold = name.normalize("NFC").toLowerCase();
        const twin = seen.get(fold);
        if (twin !== undefined)
            throw refuse(`${at}[${i}]`, twin === name ? `repeats ${JSON.stringify(name)}.` : `${JSON.stringify(name)} names the same file as ${JSON.stringify(twin)} on a case-insensitive filesystem.`);
        seen.set(fold, name);
        return name;
    });
}
export function instructionFamilyOf(spec) {
    return spec !== null && typeof spec === "object" ? spec.instructionFamily : undefined;
}
export function screenNestedMemory(spec, projectMemory) {
    const v = instructionFamilyOf(spec);
    if (v === undefined)
        return undefined;
    if (!isPlain(v))
        throw refuse(FIELD, `must be an object (got ${describeRejectedValue(v)}).`);
    const retired = retiredKeyOf(v, RETIRED_INSTRUCTION_FAMILY_KEYS);
    if (retired !== undefined)
        throw retiredKeyRefusal({ key: `instructionFamily.${retired.key}`, replacement: retired.replacement }, "TaskSpec");
    onlyKeys(v, ["files", "rulesDirs", "alternate", "localFiles", "includes", "additionalDirectories", "externalIncludes", "hostRules"], FIELD);
    const flag = (key) => {
        const f = v[key];
        if (f !== undefined && typeof f !== "boolean")
            throw refuse(`${FIELD}.${key}`, `must be a boolean (got ${describeRejectedValue(f)}).`);
        return f === true;
    };
    const seen = new Map();
    const seenDirs = new Map();
    const files = v["files"] === undefined ? [] : screenNames(v["files"], `${FIELD}.files`, seen);
    const rulesDirs = v["rulesDirs"] === undefined ? [] : screenNames(v["rulesDirs"], `${FIELD}.rulesDirs`, seenDirs);
    let alternate;
    if (v["alternate"] !== undefined) {
        const a = v["alternate"];
        const at = `${FIELD}.alternate`;
        if (!isPlain(a))
            throw refuse(at, `must be an object (got ${describeRejectedValue(a)}).`);
        onlyKeys(a, ["files", "rulesDirs", "when"], at);
        const when = a["when"];
        if (when !== "absent" && when !== "also")
            throw refuse(`${at}.when`, `must be "absent" or "also" (got ${describeRejectedValue(when)}).`);
        const altFiles = screenNames(a["files"], `${at}.files`, seen);
        const altRules = a["rulesDirs"] === undefined ? [] : screenNames(a["rulesDirs"], `${at}.rulesDirs`, seenDirs);
        alternate = Object.freeze({ files: Object.freeze(altFiles), rulesDirs: Object.freeze(altRules), when });
    }
    const localFiles = v["localFiles"] === undefined ? [] : screenNames(v["localFiles"], `${FIELD}.localFiles`, seen);
    const includes = flag("includes");
    const additionalDirectories = flag("additionalDirectories");
    const approvals = screenApprovedPaths(v["externalIncludes"]);
    const host = v["hostRules"] === undefined ? { kept: [], skipped: [], names: [] } : screenHostRules(v["hostRules"]);
    if (files.length === 0 && rulesDirs.length === 0 && alternate === undefined && localFiles.length === 0 && v["hostRules"] === undefined)
        throw refuse(FIELD, "names nothing to load (no files, rulesDirs, alternate, localFiles or hostRules) — omit it instead.");
    if (projectMemory === "disabled")
        return undefined;
    return Object.freeze({ files: Object.freeze(files), rulesDirs: Object.freeze(rulesDirs), ...(alternate !== undefined ? { alternate } : {}), localFiles: Object.freeze(localFiles), includes, additionalDirectories, externalIncludes: Object.freeze(approvals.kept), externalIncludesSkipped: Object.freeze(approvals.skipped), hostRules: Object.freeze(host.kept), hostNames: Object.freeze(host.names), hostSkipped: Object.freeze(host.skipped) });
}
function screenApprovedPaths(v) {
    const at = `${FIELD}.externalIncludes`;
    if (v === undefined || v === false)
        return { kept: [], skipped: [] };
    if (!Array.isArray(v))
        throw refuse(at, `must be false or a list of the absolute paths approved (got ${describeRejectedValue(v)}) — no approval covers every file: list each file by the value the engine named it by (\`instructions.withheld\`'s \`detail.target\`).`);
    const entries = Array.from(v).map((p, i) => {
        if (typeof p !== "string")
            throw refuse(`${at}[${i}]`, `must be a string (got ${describeRejectedValue(p)}).`);
        if (p.length <= ABSOLUTE_HOST_PATH_MAX && (p.includes("\u0000") || !isAbsoluteForFamily("own", p)))
            throw refuse(`${at}[${i}]`, "must be an absolute path without NUL — the value the engine named the file by (`detail.target`, or `detail.path`), not the `@` text as written.");
        return p;
    });
    const kept = [];
    const skipped = [];
    for (const [i, p] of entries.entries()) {
        const why = i >= NESTED_MEMORY_MAX_APPROVED_PATHS ? "over_count" : p.length > ABSOLUTE_HOST_PATH_MAX ? "long_path" : undefined;
        if (why === undefined)
            kept.push(p);
        else
            skipped.push(Object.freeze({ path: p, why }));
    }
    return { kept, skipped };
}
function screenHostRules(v) {
    const at = `${FIELD}.hostRules`;
    if (!Array.isArray(v))
        throw refuse(at, `must be an array (got ${describeRejectedValue(v)}).`);
    const entries = Array.from(v).map((r, i) => {
        const ra = `${at}[${i}]`;
        if (!isPlain(r))
            throw refuse(ra, `must be an object (got ${describeRejectedValue(r)}).`);
        onlyKeys(r, ["level", "name", "text", "rule"], ra);
        const level = r["level"];
        if (!HOST_TEXT_LEVELS.includes(level))
            throw refuse(`${ra}.level`, `must be one of ${HOST_TEXT_LEVELS.map((l) => JSON.stringify(l)).join(", ")} (got ${describeRejectedValue(level)}).`);
        const name = r["name"];
        if (typeof name !== "string" || name.length === 0 || name.includes("\u0000"))
            throw refuse(`${ra}.name`, `must be a non-empty string without NUL (got ${describeRejectedValue(name)}).`);
        const text = r["text"];
        if (typeof text !== "string")
            throw refuse(`${ra}.text`, `must be a string (got ${describeRejectedValue(text)}).`);
        const rule = r["rule"];
        if (rule !== undefined && typeof rule !== "boolean")
            throw refuse(`${ra}.rule`, `must be a boolean (got ${describeRejectedValue(rule)}).`);
        return Object.freeze({ level: level, name, text, rule: rule === true });
    });
    const kept = [];
    const skipped = [];
    const seen = new Set();
    for (const [i, e] of entries.entries()) {
        const why = i >= NESTED_MEMORY_MAX_HOST_RULES ? "over_count" : seen.has(e.name) ? "repeated" : e.name.length > ABSOLUTE_HOST_PATH_MAX ? "long_name" : Buffer.byteLength(e.text, "utf8") > INSTRUCTION_FILE_MAX_BYTES ? "large_text" : undefined;
        seen.add(e.name);
        if (why === undefined)
            kept.push(e);
        else
            skipped.push(Object.freeze({ name: e.name, why }));
    }
    return { kept, skipped, names: entries.map((e) => e.name) };
}
export function instructionEchoOf(label, layer, withdrawn) {
    return { source: layer === "root" ? "project_instructions" : "nested_memory", preview: steeringPreview(withdrawn ? `${label} (withdrawn: it no longer applies)` : label) };
}
export function instructionEchoTo(queue, ident, attach) {
    return (label, layer, withdrawn) => {
        queue.push({ type: "steering_injected", ...instructionEchoOf(label, layer, withdrawn), ...ident() });
        attach.attachmentsInjected += 1;
    };
}
export async function restateInstructionFiles(lane, seat, echo) {
    let load;
    try {
        load = await lane.load({ echo });
    }
    catch (err) {
        seat.report?.(asThrownError(err));
        return;
    }
    if (load === undefined)
        return;
    for (const [i, f] of load.frames.entries()) {
        try {
            await appendAdmittedRow(seat.admitRows, seat.session, { role: "user", content: [...f.seed.content], timestamp: Date.now(), provenance: "engine-note", attachment: f.seed.attachment });
            f.commit?.();
        }
        catch (err) {
            load.release(load.frames.slice(i).map((x) => x.seed.attachment.ordinal));
            seat.report?.(new Error(`instruction files could not be written to the transcript after the compaction (the next load owes them again): ${asThrownError(err).message}`));
            return;
        }
    }
}
const foundByLane = (i) => i.rule === "any" || i.from !== undefined;
const layerOf = (level) => (level === "" ? "root" : "nested");
const itemId = (i) => `${i.kind}\u0000${i.path}`;
const HOST_RULE_KEY = "host-rule:";
export function createNestedMemoryLane(seat) {
    const decl = seat.declaration;
    const hands = seat.env !== undefined ? seat : undefined;
    const state = hands?.state ?? new Map();
    const win = hands !== undefined && pathFamilyOf({ root: hands.root }) === "win";
    const sep = win ? "\\" : "/";
    const baseOf = (dir) => (dir.endsWith(sep) ? dir.slice(0, -1) : dir);
    const roots = hands === undefined ? [] : [{ base: baseOf(hands.root), canonical: hands.root }];
    for (const r of decl.additionalDirectories ? (hands?.additionalRoots ?? []) : []) {
        const base = baseOf(r.canonical);
        if (!roots.some((x) => x.base === base))
            roots.push({ base, canonical: r.canonical, directory: r.directory });
    }
    const insideItsRoots = (r, key) => withinAnyRoot([roots[r].canonical, roots[0].canonical], key);
    const absIn = (r, rel) => (rel === "" ? roots[r].base : `${roots[r].base}${sep}${win ? rel.replaceAll("/", "\\") : rel}`);
    const relIn = (r, key) => (roots[r] === undefined ? undefined : relUnder(roots[r].base, key));
    const relUnder = (base, key) => {
        const x = base === "" ? (key.startsWith(sep) ? key.slice(sep.length) : null) : relativeUnderRoot(key, base);
        return x === null ? undefined : win ? x.replaceAll("\\", "/") : x;
    };
    const abs = (rel) => absIn(0, rel);
    const relOf = (key) => relIn(0, key);
    const levelsOf = (rel) => {
        const segs = rel.split("/");
        return segs.slice(0, -1).map((_, i) => segs.slice(0, i + 1).join("/"));
    };
    const queue = [];
    const queued = new Map();
    const rankOf = (i) => (i.level === "" ? i.root : roots.length);
    const displaced = new Map();
    const claim = (i) => {
        const id = itemId(i);
        const held = queued.get(id);
        if (held !== undefined) {
            const at = queue.indexOf(held);
            if (rankOf(held) <= rankOf(i) || at < 0) {
                if (held.kind === "file" && i.kind === "file" && foundByLane(held) && foundByLane(i) && i.approved === true && held.approved !== true)
                    Object.assign(held, { owner: i.owner, approved: true, from: i.from });
                return false;
            }
            queue.splice(at, 1);
            if (i.kind === "file" && foundByLane(i) && held.kind === "file" && !foundByLane(held))
                displaced.set(id, held);
        }
        queued.set(id, i);
        return true;
    };
    const inFlight = new Set();
    const includesBy = new Map();
    let hostRetry = false;
    let seen;
    let alternateOn = decl.alternate === undefined || hands === undefined ? false : decl.alternate.when === "also" ? true : undefined;
    const entryId = (e) => `${e.hash}\u0000${e.lastReadAt ?? ""}\u0000${e.witnesses?.join("\u0001") ?? ""}`;
    const isAccess = (e) => e.seededFromContext !== true && !isInstructionLaneEntry(e);
    const deliveredEntry = (key) => {
        const e = state.get(key);
        return e !== undefined && isInstructionLaneEntry(e) ? e : undefined;
    };
    const withdrawing = new Set();
    const asked = new Set();
    const asksAgain = (i) => asked.has(i.path) && (i.kind === "listing" || i.rule === "any");
    const queueAgain = (items) => {
        for (const i of items) {
            let at = queue.length - 1;
            while (at >= 0 && (queue[at].root !== i.root || queue[at].level !== i.level))
                at--;
            queue.splice(at + 1, 0, i);
        }
    };
    const queueOwed = (items, front) => {
        const first = items.filter((i) => !asksAgain(i));
        if (front)
            queue.unshift(...first);
        else
            queue.push(...first);
        queueAgain(items.filter(asksAgain));
    };
    const second = (r) => r === 0 && alternateOn === true;
    const activeNames = (r) => [...decl.files, ...(second(r) ? decl.alternate.files : [])];
    const activeRules = (r) => [...decl.rulesDirs, ...(second(r) ? decl.alternate.rulesDirs : [])];
    const memberAt = (rel, level, names, rules) => {
        const at = level === "" ? rel : rel.startsWith(`${level}/`) ? rel.slice(level.length + 1) : undefined;
        if (at === undefined)
            return undefined;
        if (names.includes(at))
            return "name";
        if (decl.localFiles.includes(at))
            return "local";
        return rules.some((d) => at.startsWith(`${d}/`) && at.endsWith(".md")) ? "rule" : undefined;
    };
    const declaredOf = roots.map((_, r) => ({
        names: [...decl.files, ...(r === 0 ? (decl.alternate?.files ?? []) : [])],
        rules: [...decl.rulesDirs, ...(r === 0 ? (decl.alternate?.rulesDirs ?? []) : [])],
    }));
    const declaredNamesOf = (r) => declaredOf[r].names;
    const declaredRulesOf = (r) => declaredOf[r].rules;
    const rootLevelOf = (key) => roots.findIndex((_, r) => {
        const rel = relIn(r, key);
        return rel !== undefined && rel !== "" && memberAt(rel, "", declaredNamesOf(r), declaredRulesOf(r)) !== undefined;
    });
    const isMember = (key, at) => {
        if (rootLevelOf(key) >= 0)
            return true;
        const rel = relOf(key);
        return at === "any" && rel !== undefined && rel !== "" && levelsOf(rel).some((level) => memberAt(rel, level, declaredNamesOf(0), declaredRulesOf(0)) !== undefined);
    };
    const tellLoadedOutside = (path, target) => {
        const leg = seat.leg();
        if (leg === undefined)
            return;
        const d = announceDigest(INSTRUCTIONS_OUTSIDE_ROOT, JSON.stringify([path, target]));
        if ((leg.announcedListingsRef.advisories ?? []).includes(d))
            return;
        leg.announcedListingsRef.advisories = withAnnounceDigests(leg.announcedListingsRef.advisories, [d]);
        leg.frameReceipts.listingSnapshotOwed = true;
        if (agentIdOf(leg.hookIdentity) !== undefined)
            return;
        const r = rootLevelOf(path);
        const what = r === 0 ? "An instruction file of the task root" : r > 0 ? "An instruction file of an additional working directory" : "An instruction file of a directory the model accessed";
        const from = r > 0 ? "that directory and the task root" : "the task root";
        deliverEngineNotice(seat.deps.onNotice, {
            code: INSTRUCTIONS_OUTSIDE_ROOT,
            message: `${what} was loaded from outside ${from}: ${path} leads to ${target}. If that is not meant, replace it with a file inside ${from}, or turn the project's instruction files off for the request.`,
            detail: { path, target, sessionId: leg.sessionId, runId: leg.runId },
        });
    };
    const tellTruncated = (path, keptChars, droppedChars, supply) => {
        const leg = seat.leg();
        if (leg === undefined)
            return;
        const d = announceDigest(INSTRUCTIONS_TRUNCATED, JSON.stringify([path]));
        if ((leg.announcedListingsRef.advisories ?? []).includes(d))
            return;
        leg.announcedListingsRef.advisories = withAnnounceDigests(leg.announcedListingsRef.advisories, [d]);
        leg.frameReceipts.listingSnapshotOwed = true;
        if (agentIdOf(leg.hookIdentity) !== undefined)
            return;
        const what = supply === "content_text" ? "An instruction text the deployment supplied" : "An instruction file";
        deliverEngineNotice(seat.deps.onNotice, {
            code: INSTRUCTIONS_TRUNCATED,
            message: `${what} was cut to fit: ${path} — its frame in the model's conversation holds the first ${keptChars} characters and leaves out the last ${droppedChars}. Shorten it, or split it into files the family reads, to have all of it read.`,
            detail: { path, keptChars, droppedChars, sessionId: leg.sessionId, runId: leg.runId },
        });
    };
    const levelItems = (r, level) => {
        const items = [];
        const add = (i) => {
            if (claim(i))
                items.push(i);
        };
        const join = (name) => absIn(r, level === "" ? name : `${level}/${name}`);
        const names = activeNames(r);
        const rules = activeRules(r);
        const locals = () => decl.localFiles.forEach((name) => add({ kind: "file", root: r, level, path: join(name), rule: "none", depth: 0, owner: "local" }));
        for (const name of names)
            add({ kind: "file", root: r, level, path: join(name), rule: "none", depth: 0 });
        if (level !== "")
            locals();
        for (const dir of rules)
            add({ kind: "listing", root: r, level, path: join(dir) });
        if (level === "")
            locals();
        for (const [key, e] of state) {
            const rel = relIn(r, key);
            const member = rel === undefined || rel === "" || !isInstructionLaneEntry(e) ? undefined : memberAt(rel, level, names, rules);
            if (member !== undefined)
                add({ kind: "file", root: r, level, path: key, rule: member === "rule" ? "any" : "none", depth: 0, ...(member === "local" ? { owner: "local" } : {}) });
        }
        return items;
    };
    const handBack = (rs) => {
        for (const r of rs) {
            inFlight.delete(r.key);
            withdrawing.delete(r.key);
        }
        if (rs.some((r) => r.key.startsWith(HOST_RULE_KEY)))
            hostRetry = true;
        const back = rs.filter((r) => !r.key.startsWith(HOST_RULE_KEY)).map((r) => r.item).filter(claim);
        queue.unshift(...back);
    };
    let primed;
    const firstLoadIncluded = new Map();
    const firstLoadWithheld = new Map();
    const hostTexts = decl.hostRules.map((t) => {
        const shown = processInstructionText(normalizeFileText(t.text), decl.includes);
        return { ...t, shown, owner: OWNER_OF_LEVEL[t.level], anchored: hands !== undefined && isAbsoluteHostPath(t.name), conditional: t.rule && shown.globs !== undefined };
    });
    const anchorOf = (t) => {
        if (!t.anchored || t.level === "user" || t.level === "managed")
            return roots[0].base;
        const name = win ? t.name.replaceAll("/", "\\") : t.name;
        for (const d of [...decl.rulesDirs, ...(decl.alternate?.rulesDirs ?? [])]) {
            const at = name.indexOf(`${sep}${win ? d.replaceAll("/", "\\") : d}${sep}`);
            if (at >= 0)
                return name.slice(0, at);
        }
        return baseOf(lexicalViewOf("..", name));
    };
    const hostKeys = new Map();
    const hostKeyOf = async (name) => {
        if (!hostKeys.has(name)) {
            const r = await hands.reader.resolveTarget(name, { signal: seat.signal }).catch(() => undefined);
            hostKeys.set(name, r?.ok === true ? r.key : undefined);
        }
        return hostKeys.get(name);
    };
    const collect = async (ask, echo) => {
        const leg = seat.leg();
        if (leg === undefined || seat.signal.aborted)
            return [];
        const forManifest = ask.forManifest === true;
        const recordIncluded = (item, key) => {
            if (forManifest && item.from !== undefined && !firstLoadIncluded.has(key)) {
                firstLoadIncluded.set(key, Object.freeze({ path: key, includedBy: item.from.key, spelled: item.from.spelled }));
            }
        };
        const accesses = new Set();
        const current = new Map();
        const firstLoad = seen === undefined;
        for (const [key, e] of state) {
            current.set(key, entryId(e));
            const rel = relOf(key);
            if (rel !== undefined && rel !== "" && isAccess(e))
                accesses.add(rel);
        }
        const dirty = new Set([""]);
        const touch = (rel) => {
            for (const l of levelsOf(rel))
                dirty.add(l);
        };
        for (const key of ask.triggers ?? []) {
            const rel = relOf(key);
            if (rel === undefined || rel === "")
                continue;
            accesses.add(rel);
            touch(rel);
        }
        if (seen === undefined)
            for (const rel of accesses)
                touch(rel);
        else {
            for (const [key, id] of current) {
                const rel = relOf(key);
                if (rel !== undefined && rel !== "" && seen.get(key) !== id && isAccess(state.get(key)))
                    touch(rel);
            }
            for (const key of seen.keys()) {
                const rel = relOf(key);
                if (rel !== undefined && rel !== "" && !current.has(key))
                    touch(rel);
            }
        }
        seen = current;
        const pending = new Set(ask.triggers ?? []);
        const p = { count: 0 };
        if (alternateOn === undefined) {
            p.count += decl.files.length;
            const atRoot = await Promise.all(decl.files.map((name) => hands.env.fileInfo(abs(name), seat.signal).catch(() => undefined)));
            alternateOn = !atRoot.some((info) => info?.ok === true && info.value.kind !== "directory");
        }
        queueOwed(roots.flatMap((_, r) => levelItems(r, "")), true);
        for (const level of [...dirty].sort((a, b) => a.split("/").length - b.split("/").length || (a < b ? -1 : a > b ? 1 : 0)))
            if (level !== "" && [...accesses].some((r) => r.startsWith(`${level}/`)))
                queueOwed(levelItems(0, level), false);
        queue.sort((a, b) => rankOf(a) - rankOf(b));
        const probes = NESTED_MEMORY_PROBES_PER_LOAD * roots.length;
        const model = leg.harness.getModel();
        const cpt = model.charsPerToken ?? 4;
        const cap = instructionFileCap(model.contextWindow, cpt);
        const told = new Set(leg.announcedListingsRef.advisories ?? []);
        const fresh = [];
        const delegated = agentIdOf(leg.hookIdentity) !== undefined;
        const once = (lane, path, why, say) => {
            const d = announceDigest(lane, `${path}\n${why}`);
            if (told.has(d))
                return;
            told.add(d);
            fresh.push(d);
            say();
        };
        const withheld = (item, reason, past, target, blockedAfterApproval, ruleLayer, whyText) => {
            if (forManifest && (item.rule === "any" || item.from !== undefined || reason === "too_many_texts" || reason === "unanchored")) {
                const wKey = `${item.path}\u0000${reason}\u0000${target ?? ""}\u0000${item.from?.key ?? ""}\u0000${item.from?.spelled ?? ""}`;
                if (!firstLoadWithheld.has(wKey)) {
                    firstLoadWithheld.set(wKey, Object.freeze({
                        path: item.path,
                        reason,
                        ...(target !== undefined ? { target } : {}),
                        ...(item.from !== undefined ? { includedBy: item.from.key, spelled: item.from.spelled } : {}),
                        ...(blockedAfterApproval !== undefined ? { blockedAfterApproval } : {}),
                    }));
                }
            }
            once(INSTRUCTIONS_WITHHELD, item.path, target === undefined ? reason : `${reason}\n${target}`, () => {
                if (delegated)
                    return;
                const path = item.path;
                const r = rootLevelOf(path);
                const what = past !== undefined ? `An instruction text the deployment supplied, the first of ${past} past the ${NESTED_MEMORY_MAX_HOST_RULES} a task carries,` : item.from !== undefined ? `An instruction file that ${item.from.key} includes (\`@${item.from.spelled}\`)` : `An instruction file of ${r === 0 ? "the task root" : r > 0 ? "an additional working directory" : "a directory the model accessed"}`;
                const via = item.from !== undefined ? { includedBy: item.from.key, spelled: item.from.spelled } : {};
                const why = whyText ?? (reason === "outside_its_root" && item.root === 0 ? "its real location, links followed, is not under the task root" : WITHHELD_TEXT[reason]);
                deliverEngineNotice(seat.deps.onNotice, {
                    code: INSTRUCTIONS_WITHHELD,
                    message: `${what} was not loaded: ${path} (${why}). ${WITHHELD_WAY_OUT[reason]}`,
                    detail: { path, reason, sessionId: leg.sessionId, runId: leg.runId, ...via, ...(target !== undefined ? { target } : {}), ...(reason === "rule_denied" && ruleLayer !== undefined ? { ruleLayer } : {}) },
                });
            });
        };
        const tellOperator = (lane, path, why, sentence) => once(lane, path, why, () => {
            try {
                seat.deps.onError?.(new Error(sentence), { phase: "degraded", sessionId: leg.sessionId, classification: "attachment-read" });
            }
            catch {
            }
        });
        const unread = (path, why) => tellOperator("nested_memory_unread", path, why, `instruction file ${path} was not loaded: ${why}`);
        const unlimited = (path) => tellOperator("nested_memory_rule_paths", path, "no_limit", `instruction rule ${path} names \`paths:\` but it reads as no limit (nothing listed, only \`**\`, or a form the engine does not recognise), so the rule applies to every file; to limit it, list the globs (\`paths:\` then \`- src/**\` lines, or \`paths: [src/**, lib/**]\`); if every file is meant, remove the key`);
        const spansLines = (path) => tellOperator("nested_memory_rule_paths", path, "spans_lines", `instruction rule ${path} gives \`paths:\` as one text over several lines, which reads as a single glob that matches no file, so the rule is never loaded; for several globs list them (\`paths:\` then \`- src/**\` lines) or write them on one line separated by commas (\`paths: src/**, lib/**\`)`);
        const outside = new Map();
        const refusedOutside = (item, wide, key, target, targetOk = false) => {
            const held = outside.get(item.path);
            const edge = !foundByLane(item) || item.approved === true;
            const told = held === undefined || (edge && !held.edge) ? { item, edge, key: key ?? item.path, target, targetOk } : held;
            outside.set(item.path, { ...told, wide: wide || held?.wide === true });
        };
        const reads = [];
        const withdraw = (key, item) => {
            if (inFlight.has(key))
                return;
            inFlight.add(key);
            withdrawing.add(key);
            const layer = layerOf(item.level);
            reads.push({
                key,
                item,
                read: {
                    supply: "path",
                    owner: item.kind === "file" ? (item.owner ?? "repository") : "repository",
                    layer,
                    label: key,
                    text: "",
                    withdraws: true,
                    record: () => {
                        if (deliveredEntry(key) !== undefined)
                            retireRead(state, key);
                        seen?.delete(key);
                        inFlight.delete(key);
                        withdrawing.delete(key);
                        echo.fn?.(key, layer, true);
                    },
                },
            });
        };
        const visited = new Set();
        const deadlineAt = Date.now() + ORG_ADJUDICATION_TIMEOUT_MS;
        let approvedKeys;
        const approvedByRequest = async (key) => {
            if (key === undefined || decl.externalIncludes.length === 0)
                return false;
            approvedKeys ??= decl.externalIncludes.map((p) => hands.reader.resolveTarget(p, { signal: seat.signal }).then(judgedKeyOf, () => undefined));
            return Promise.any(approvedKeys.map((k) => k.then((at) => (at === key ? true : Promise.reject(new Error("another file")))))).catch(() => false);
        };
        const ruleApplies = (globs, r, level) => [...accesses].some((a) => {
            const rel = relIn(r, abs(a));
            return rel !== undefined && rel !== "" && (level === "" || rel.startsWith(`${level}/`)) && ruleGlobsMatch(globs, level === "" ? rel : rel.slice(level.length + 1));
        });
        const hostApplies = (t) => {
            const anchor = anchorOf(t);
            return [...accesses].some((a) => {
                const rel = relUnder(anchor, abs(a));
                return rel !== undefined && rel !== "" && ruleGlobsMatch(t.shown.globs, rel);
            });
        };
        const stats = new Map();
        const statsAhead = (first) => {
            if (first.kind !== "file" || stats.has(first.path))
                return;
            const room = Math.max(1, Math.min(NESTED_MEMORY_STAT_BATCH, probes - p.count));
            const batch = [first, ...queue.filter((i) => i.kind === "file" && !stats.has(i.path))].slice(0, room);
            p.count += batch.length;
            for (const i of batch)
                stats.set(i.path, hands.env.fileInfo(i.path, seat.signal).catch((err) => ({ ok: false, error: { code: "io", message: thrownText(err) } })));
        };
        const probeFile = async (item) => {
            asked.add(item.path);
            const member = displaced.get(itemId(item));
            displaced.delete(itemId(item));
            const info = await stats.get(item.path);
            if (!info.ok) {
                if (info.error.code === "not_found" && deliveredEntry(item.path) !== undefined)
                    withdraw(item.path, item);
                else if (!QUIET_ERRORS.has(info.error.code))
                    unread(item.path, info.error.message);
                return [];
            }
            if (info.value.kind === "directory")
                return [];
            const heldToItsRoots = async (key) => foundByLane(item) && item.approved !== true && !(await approvedByRequest(key));
            const outsideItsRoot = (key, judged, targetOk) => {
                refusedOutside(item, false, key, judged, targetOk);
                return member !== undefined ? [member] : [];
            };
            const target = await hands.reader.resolveTarget(item.path, { signal: seat.signal });
            if (!target.ok) {
                const card = target.refusal.details?.type;
                if (card === "read_path_denied")
                    withheld(item, "rule_denied");
                else if (card === "path_not_in_root") {
                    const judged = judgedKeyOf(target);
                    return (await heldToItsRoots(judged)) ? outsideItsRoot(undefined, judged, false) : (refusedOutside(item, true), []);
                }
                return [];
            }
            const key = target.key;
            if (!insideItsRoots(item.root, key) && (await heldToItsRoots(key)))
                return outsideItsRoot(key, key, true);
            if (visited.has(key) || inFlight.has(key))
                return [];
            const stat = info.value.kind === "symlink" ? await hands.env.fileInfo(key, seat.signal).catch(() => undefined) : info;
            if (stat === undefined || !stat.ok)
                return [];
            const mtime = stat.value.mtimeMs;
            const entry = state.get(key);
            if (entry !== undefined && entry.lastReadAt === mtime && (!decl.includes || includesBy.has(key))) {
                visited.add(key);
                recordIncluded(item, key);
                return includesAt(includesBy.get(key) ?? [], item, key);
            }
            p.count++;
            const face = hands.readFace();
            const held = await hands.reader.openBound(key, seat.signal);
            try {
                const verdict = await hands.judge({ file_path: item.path, ...(face !== undefined ? { face } : {}) }, NESTED_MEMORY_PROBE_FACE, { deadlineAt });
                if (verdict.verdict !== "no_objection") {
                    withheld(item, readJudgeBlockOf(verdict), undefined, undefined, undefined, verdict.verdict === "deny" ? verdict.layer : undefined);
                    return [];
                }
                if (verdict.judged !== undefined && verdict.judged !== key) {
                    withheld(item, "target_moved");
                    return [];
                }
                visited.add(key);
                const t = await hands.reader.readText(key, { signal: seat.signal }, { judgedKey: key, capBytes: INSTRUCTION_FILE_MAX_BYTES, opened: { key, opening: held } });
                return admit(t, item, key, mtime, entry);
            }
            finally {
                if (held.kind === "bound")
                    await held.object.close().catch(() => undefined);
            }
        };
        const admit = (t, item, key, mtime, entry) => {
            if (t.kind !== "text") {
                if (t.kind === "refused")
                    withheld(item, "rule_denied");
                else if (t.kind === "moved")
                    withheld(item, "target_moved");
                else if (t.kind !== "absent")
                    unread(item.path, t.kind === "not_text" ? "it is not text" : t.kind === "oversize" ? `it is over ${INSTRUCTION_FILE_MAX_BYTES} bytes` : "the environment could not read it");
                return [];
            }
            const text = normalizeFileText(t.text);
            const hash = sha256(text);
            const shown = processInstructionText(text, decl.includes);
            if (item.rule !== "none" && shown.noLimit === true)
                unlimited(item.path);
            if (item.rule !== "none" && shown.spansLines === true)
                spansLines(item.path);
            if (item.rule !== "none" && shown.globs !== undefined && !ruleApplies(shown.globs, item.root, item.level))
                return [];
            const targets = includeTargetsOf(shown.includes, key);
            includesBy.set(key, targets);
            const more = includesAt(targets, item, key);
            if (pending.has(key))
                return more;
            if (entry !== undefined && entry.hash === hash) {
                recordIncluded(item, key);
                return more;
            }
            if (shown.content.trim() === "") {
                if (entry !== undefined && isInstructionLaneEntry(entry))
                    withdraw(key, item);
                return more;
            }
            const cut = cutInstructionText(shown.content, cap, cpt);
            const totalLines = countLines(text);
            const whole = shown.content === text && cut.note === undefined;
            const recorded = { hash, totalLines, truncated: !whole, ...(whole ? { view: { start: 1, end: totalLines } } : { isPartialView: true }) };
            inFlight.add(key);
            const layer = layerOf(item.level);
            const outsideItsRoots = !foundByLane(item) && !insideItsRoots(item.root, key);
            const read = {
                supply: "path",
                owner: item.owner ?? "repository",
                ...(item.from !== undefined ? { included: true } : {}),
                layer,
                label: key,
                text: cut.text,
                ...(cut.note !== undefined ? { cut: cut.note } : {}),
                observation: { key, entry: recorded, stampedAt: mtime },
                record: (transmission) => {
                    const landed = { ...recorded, lastReadAt: mtime, witnesses: witnessesAfterDelivery(state.get(key), recorded, transmission) };
                    state.set(key, landed);
                    seen?.set(key, entryId(landed));
                    inFlight.delete(key);
                    echo.fn?.(key, layer, false);
                    if (outsideItsRoots)
                        tellLoadedOutside(item.path, key);
                    if (cut.note !== undefined)
                        tellTruncated(key, cut.text.length, shown.content.length - cut.text.length, "path");
                },
            };
            reads.push({ read, item, key });
            recordIncluded(item, key);
            return more;
        };
        const includeTargetsOf = (paths, from) => {
            const dir = lexicalViewOf("..", from);
            const home = hands.env.homeDir;
            return paths.flatMap((spelled) => {
                if (!isTextIncludeTarget(spelled))
                    return [];
                const at = spelled.startsWith("~/") ? (home === undefined ? undefined : expandHomeTilde(spelled, home)) : spelled;
                return [{ path: at === undefined ? undefined : lexicalViewOf(at, dir), spelled }];
            });
        };
        const includesAt = (targets, item, key) => item.depth + 1 >= INSTRUCTION_INCLUDE_MAX_DEPTH
            ? []
            : targets.flatMap((t) => {
                const next = { kind: "file", root: item.root, level: item.level, path: t.path ?? t.spelled, rule: "none", depth: item.depth + 1, from: { key, spelled: t.spelled }, ...(item.owner !== undefined ? { owner: item.owner } : {}), ...(item.approved === true ? { approved: true } : {}) };
                if (t.path !== undefined)
                    return [next];
                withheld(next, "admission_unknown", undefined, undefined, undefined, undefined, "the environment declares no home directory, so a ~/ path cannot be placed");
                return [];
            });
        const probeListing = async (item) => {
            asked.add(item.path);
            p.count++;
            const listed = await hands.env.listDir(item.path, seat.signal).catch((err) => ({ ok: false, error: { code: "io", message: thrownText(err) } }));
            if (!listed.ok) {
                if (!QUIET_ERRORS.has(listed.error.code))
                    unread(item.path, listed.error.message);
                return [];
            }
            const entries = [...listed.value].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
            return [
                ...entries.filter((e) => e.kind !== "directory" && e.name.endsWith(".md")).map((e) => ({ kind: "file", root: item.root, level: item.level, path: e.path, rule: "any", depth: 0 })),
                ...entries.filter((e) => e.kind === "directory").map((e) => ({ kind: "listing", root: item.root, level: item.level, path: e.path })),
            ];
        };
        const budget = NESTED_MEMORY_FRAME_BUDGET_FILES * cap;
        let chars = 0;
        const drain = async () => {
            while (queue.length > 0 && p.count < probes && !seat.signal.aborted && chars <= budget) {
                const item = queue.shift();
                queued.delete(itemId(item));
                statsAhead(item);
                const before = reads.length;
                let more;
                try {
                    more = item.kind === "file" ? await probeFile(item) : await probeListing(item);
                }
                catch (err) {
                    unread(item.path, thrownText(err));
                    more = [];
                }
                for (const r of reads.slice(before))
                    chars += r.read.text.length;
                queueOwed(more.filter(claim), true);
            }
        };
        await drain();
        const familyReads = reads.splice(0);
        const past = decl.hostSkipped.filter((s) => s.why === "over_count");
        if (past.length > 0)
            withheld({ path: past[0].name }, "too_many_texts", past.length);
        for (const s of decl.hostSkipped)
            if (s.why !== "over_count")
                tellOperator("nested_memory_host_text", s.name, s.why, `instruction text ${shortName(s.name)} was not loaded: ${HOST_SKIP_TEXT[s.why]}`);
        const pastApprovals = decl.externalIncludesSkipped.filter((s) => s.why === "over_count");
        if (pastApprovals.length > 0)
            tellOperator("nested_memory_approval", pastApprovals[0].path, "over_count", `${FIELD}.externalIncludes lists ${NESTED_MEMORY_MAX_APPROVED_PATHS + pastApprovals.length} paths: the first ${NESTED_MEMORY_MAX_APPROVED_PATHS} are read as approvals, the ${pastApprovals.length} after them (the first: ${shortName(pastApprovals[0].path)}) are not, so a file only they approve is not loaded`);
        for (const s of decl.externalIncludesSkipped)
            if (s.why === "long_path")
                tellOperator("nested_memory_approval", s.path, s.why, `${FIELD}.externalIncludes holds a path of ${s.path.length} characters, over ${ABSOLUTE_HOST_PATH_MAX}: it is not read as an approval (${shortName(s.path)})`);
        const rootLayer = [];
        const nestedLayer = [];
        const hostIncludes = [];
        if (hostTexts.length > 0 || firstLoad || hostRetry) {
            hostRetry = false;
            const shownNow = lastHostTexts(await leg.session.buildContext().then((c) => c.messages).catch(() => ((hostRetry = true), [])));
            const hostRead = (name, layer, owner, cut, processedChars) => {
                const key = `${HOST_RULE_KEY}${name}`;
                inFlight.add(key);
                const read = {
                    supply: "content_text",
                    owner,
                    layer,
                    label: name,
                    text: cut?.text ?? "",
                    ...(cut === undefined ? { withdraws: true } : cut.note !== undefined ? { cut: cut.note } : {}),
                    record: () => {
                        inFlight.delete(key);
                        echo.fn?.(name, layer, cut === undefined);
                        if (cut?.note !== undefined)
                            tellTruncated(name, cut.text.length, (processedChars ?? cut.text.length) - cut.text.length, "content_text");
                    },
                };
                (layer === "root" ? rootLayer : nestedLayer).push({ key, item: { kind: "file", root: 0, level: "", path: key, rule: "none", depth: 0 }, read });
            };
            for (const t of hostTexts) {
                if (inFlight.has(`${HOST_RULE_KEY}${t.name}`))
                    continue;
                if (t.rule && t.shown.noLimit === true)
                    unlimited(t.name);
                if (t.rule && t.shown.spansLines === true)
                    spansLines(t.name);
                const last = shownNow.get(t.name);
                if (t.shown.content.trim() === "") {
                    if (last?.text !== undefined)
                        hostRead(t.name, last.layer, t.owner);
                    continue;
                }
                if (t.conditional && hands === undefined)
                    tellOperator("nested_memory_host_text", t.name, "no_files", `instruction rule ${t.name} applies where its \`paths:\` match a file the run accesses, and this run has no files: it is not loaded`);
                if (t.conditional && (hands === undefined || !hostApplies(t)))
                    continue;
                const key = t.anchored ? await hostKeyOf(t.name) : undefined;
                if (key !== undefined && !withdrawing.has(key) && (inFlight.has(key) || deliveredEntry(key) !== undefined)) {
                    tellOperator("nested_memory_host_text", t.name, "same_file", `instruction text ${t.name} is the instruction file ${key} the lane already loads: that file's frame is the one copy, the deployment's is not loaded`);
                    continue;
                }
                if (key !== undefined)
                    visited.add(key);
                const from = { kind: "file", root: 0, level: "", path: t.name, rule: "none", depth: 0, owner: t.owner, ...(t.level === "user" ? { approved: true } : {}) };
                if (t.anchored)
                    hostIncludes.push(...includesAt(includeTargetsOf(t.shown.includes, t.name), from, t.name));
                else
                    for (const spelled of t.shown.includes.filter(isTextIncludeTarget))
                        if (isAbsoluteHostPath(t.name) || spelled.startsWith("~/") || isAbsoluteForFamily("own", spelled))
                            withheld({ path: spelled, from: { key: t.name, spelled } }, "unanchored");
                const cut = cutInstructionText(t.shown.content, cap, cpt);
                const layer = t.conditional ? "nested" : "root";
                if (last?.text !== cut.text || last.layer !== layer || (last.owner !== undefined && last.owner !== t.owner))
                    hostRead(t.name, layer, t.owner, cut, t.shown.content.length);
            }
            for (const [name, last] of shownNow)
                if (last.text !== undefined && !decl.hostNames.includes(name) && !inFlight.has(`${HOST_RULE_KEY}${name}`))
                    hostRead(name, last.layer, "deployment");
        }
        queueOwed(hostIncludes.filter(claim), true);
        await drain();
        for (const r of outside.values()) {
            if (visited.has(r.key) || (inFlight.has(r.key) && !withdrawing.has(r.key)) || queued.has(itemId(r.item)))
                continue;
            let blockedAfterApproval;
            if (!r.wide && forManifest && hands !== undefined) {
                if (!r.targetOk)
                    blockedAfterApproval = "outside_roots";
                else {
                    try {
                        const face = hands.readFace();
                        const verdict = await hands.judge({ file_path: r.item.path, ...(face !== undefined ? { face } : {}) }, NESTED_MEMORY_PROBE_FACE, { deadlineAt });
                        blockedAfterApproval = readJudgeBlockOf(verdict);
                    }
                    catch (err) {
                        unread(r.item.path, thrownText(err));
                        blockedAfterApproval = "admission_unknown";
                    }
                }
            }
            withheld(r.item, r.wide ? "outside_roots" : "outside_its_root", undefined, r.wide ? undefined : r.target, blockedAfterApproval);
        }
        const includeReads = reads.splice(0);
        reads.push(...rootLayer, ...includeReads, ...familyReads, ...nestedLayer);
        if (fresh.length > 0) {
            leg.announcedListingsRef.advisories = withAnnounceDigests(leg.announcedListingsRef.advisories, fresh);
            leg.frameReceipts.listingSnapshotOwed = true;
        }
        return reads;
    };
    const fitLoad = (reads, leg) => {
        const model = leg.harness.getModel();
        const budget = NESTED_MEMORY_FRAME_BUDGET_FILES * instructionFileCap(model.contextWindow, model.charsPerToken ?? 4);
        const taken = [...reads];
        const fileTools = seat.fileTools?.();
        const disclosure = { reader: hands?.reader, mark: seat.mark, counts: seat.counts, ...(fileTools !== undefined ? { fileTools } : {}) };
        let minted = mintInstructionFrames(taken.map((r) => r.read), disclosure);
        const sizeOf = (frames) => frames.reduce((n, f) => n + f.seed.content.reduce((m, b) => m + (b.type === "text" ? b.text.length : 0), 0), 0);
        while (taken.length > 1 && sizeOf(minted.frames) > budget) {
            taken.pop();
            minted = mintInstructionFrames(taken.map((r) => r.read), disclosure);
        }
        return { taken, rest: reads.slice(taken.length), minted };
    };
    const mint = (reads) => {
        const leg = seat.leg();
        if (reads.length === 0 || leg === undefined) {
            handBack(reads);
            return undefined;
        }
        const { taken, rest, minted } = fitLoad(reads, leg);
        for (let i = rest.length - 1; i >= 0; i--)
            handBack([rest[i]]);
        return {
            inputId: minted.inputId,
            frames: minted.frames,
            chars: minted.frames.reduce((n, f) => n + f.seed.attachment.chars, 0),
            release: (ordinals) => handBack(ordinals === undefined ? taken : taken.filter((_, i) => ordinals.includes(i + 1))),
        };
    };
    return {
        async prime() {
            if (primed !== undefined)
                return;
            const echo = { fn: undefined };
            primed = { reads: await collect({ forManifest: true }, echo), echo };
        },
        async load(ask) {
            const held = primed;
            primed = undefined;
            const reads = [];
            if (held !== undefined) {
                held.echo.fn = ask.echo;
                const carried = new Set(ask.triggers ?? []);
                for (const r of held.reads) {
                    if (carried.has(r.key) && r.read.withdraws !== true)
                        inFlight.delete(r.key);
                    else
                        reads.push(r);
                }
            }
            try {
                reads.push(...(await collect(ask, { fn: ask.echo })));
            }
            catch (err) {
                handBack(reads);
                throw err;
            }
            return mint(reads);
        },
        owedAhead(triggers) {
            const leg = seat.leg();
            if (primed === undefined || leg === undefined)
                return [];
            const carried = new Set(triggers);
            const reads = primed.reads.filter((r) => !(carried.has(r.key) && r.read.withdraws !== true));
            return reads.length === 0 ? [] : fitLoad(reads, leg).minted.frames;
        },
        selected() {
            const withheldList = [...firstLoadWithheld.values()];
            if (hands === undefined) {
                return withheldList.length > 0 ? Object.freeze({ selected: Object.freeze([]), withheld: Object.freeze(withheldList) }) : undefined;
            }
            const keys = roots.map(() => new Set());
            for (const key of [...state.keys(), ...inFlight]) {
                const r = withdrawing.has(key) ? -1 : rootLevelOf(key);
                if (r >= 0)
                    keys[r].add(key);
            }
            const of = (r) => {
                const names = [...declaredNamesOf(r), ...decl.localFiles];
                const rank = (rel) => {
                    const i = names.indexOf(rel);
                    return i < 0 ? names.length : i;
                };
                return Object.freeze([...keys[r]].map((k) => relIn(r, k)).sort((a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0)));
            };
            const additional = roots.slice(1).map((x, i) => Object.freeze({ directory: x.directory, selected: of(i + 1) }));
            const included = [...firstLoadIncluded.entries()].filter(([k]) => !withdrawing.has(k) && (state.has(k) || inFlight.has(k))).map(([, v]) => v);
            return Object.freeze({
                selected: of(0),
                ...(decl.additionalDirectories ? { additionalDirectories: Object.freeze(additional) } : {}),
                ...(included.length > 0 ? { included: Object.freeze(included) } : {}),
                ...(withheldList.length > 0 ? { withheld: Object.freeze(withheldList) } : {}),
            });
        },
        isMember,
    };
}
function readJudgeBlockOf(verdict) {
    return verdict.verdict === "no_objection" ? undefined : verdict.verdict === "deny" ? "rule_denied" : verdict.verdict === "ask" ? "approval_required" : "admission_unknown";
}
export async function primeInstructionReading(lane, report) {
    try {
        await lane.prime();
    }
    catch (err) {
        report(asThrownError(err));
    }
    return lane.selected();
}
export async function primeInstructionLane(lane, manifest, report) {
    const selected = await primeInstructionReading(lane, report);
    if (selected !== undefined)
        manifest.instructions = selected;
}
function lastHostTexts(messages) {
    const out = new Map();
    for (const m of messages) {
        const a = userAttachmentOf(m);
        if (a === undefined || a.supply !== "content_text" || (a.origin !== "nested_memory" && a.origin !== "project_instructions"))
            continue;
        const content = m.content;
        const blocks = content.slice(a.dataBlocks.start, a.dataBlocks.end);
        const opening = content[0]?.type === "text" ? (content[0].text ?? "") : "";
        out.set(a.label, { text: a.withdraws !== undefined ? undefined : blocks.map((b) => (b.type === "text" ? (b.text ?? "") : "")).join(""), layer: a.origin === "project_instructions" ? "root" : "nested", owner: instructionFrameOwnerOf(opening) });
    }
    return out;
}
const HOST_SKIP_TEXT = {
    repeated: "an earlier text has the same name, and the first one is the one loaded",
    long_name: `its name is over ${ABSOLUTE_HOST_PATH_MAX} characters`,
    large_text: `it is over ${INSTRUCTION_FILE_MAX_BYTES} bytes, the bound an instruction file is read at`,
};
const shortName = (name) => (name.length > 256 ? `${name.slice(0, 256)}…` : name);
function judgedKeyOf(r) {
    if (r.ok)
        return r.key;
    const card = r.refusal.details;
    return card?.type === "path_not_in_root" && typeof card.target === "string" ? card.target : undefined;
}
const QUIET_ERRORS = new Set(["not_found", "not_directory", "aborted"]);
const WITHHELD_TEXT = {
    rule_denied: "a read rule refuses it",
    outside_roots: "it resolves outside the directories the run may read",
    approval_required: "reading it needs an approval nobody was asked for",
    admission_unknown: "the engine could not confirm it may be read",
    target_moved: "it changed while it was being checked",
    outside_its_root: "its real location, links followed, is under neither the root directory it was found in nor the task root",
    too_many_texts: `a task carries the first ${NESTED_MEMORY_MAX_HOST_RULES} texts the deployment supplies, in its order`,
    unanchored: "the text that includes it is not a file of the run's — it is named by a label, or the run has no files — so its includes are not followed",
};
const WITHHELD_WAY_OUT = {
    rule_denied: "Remove the read rule that refuses it (a built-in credential row can be removed only by the deployment), or move the file to a path no rule refuses.",
    outside_roots: "Point the link back inside those directories or make it a real file there, or add the directory it leads to among the session's additional directories.",
    approval_required: "Remove the ask rule or policy (yours, the deployment's or the organization's) that makes reading it ask; an allow rule does not override an ask.",
    admission_unknown: "A check that could not answer is retried the next time instruction files are loaded; for a `~/` include, the deployment must declare a home directory.",
    target_moved: "Nothing to change: it is checked again the next time instruction files are loaded.",
    outside_its_root: "A file the lane found outside that root and the task root is loaded only when this project approves instruction files outside it (an approval applies from the next run); otherwise put the file inside one of them or point the link at one — adding directories or rules does not change this.",
    too_many_texts: "Merge the texts, or leave out the ones not needed, so that what matters is among the first.",
    unanchored: "Copy what it says into the text that includes it: an include is followed only from a text the deployment names by its absolute path on a run that has files.",
};