@sema-agent/core
Version:
Stateless, task-oriented AI agent core
702 lines (701 loc) • 39.3 kB
JavaScript
import { canonicalRootsOnce, isAbsence, observeEnvironment } from "./shell-read-environment.js";
import { anchorSpelling, belowOwnProcessLink, isAbsoluteForFamily, isBareOwnDescriptorLink, normalizeAbsPathLexically, ownProcessSpelling, pathFamilyOf, withinAnyRoot } from "./safety.js";
import { landingsOf, noteClimb, readingsAt, withClimbedPatterns, withClimbedViews, withFloorClimbs } from "./shell-climb.js";
import { boundaryIsTheSandbox } from "../../core/remote-env.js";
import { resolveOperandSpellings, tildeNamesAnAccount } from "./bash-readonly-classifier.js";
import { judgedCandidatesOf, sedBackupNames } from "./shell-read-write-targets.js";
import { movedReads, withHomeViews } from "./shell-read-identity.js";
import { passesUnasked } from "./shell-read-device.js";
import { compileFsGlob, fsGlobClass } from "./fs-glob.js";
import { chainHopsOrNone, leafChainMayHold, symlinkChainHops } from "../../core/path-identity.js";
import { everyAncestor, repositoryTopOf } from "./shell-read-object-path.js";
const GLOB_METACHAR_RE = /[*?[]/;
export const MAX_GLOB_DIRS = 256;
export const MAX_GLOB_MATCHES = 8192;
const WRITE_LINK_HOPS = 32;
export function compileGlobSegment(pattern) {
if (pattern.includes("\\"))
return undefined;
const tokens = [];
for (let i = 0; i < pattern.length; i++) {
const ch = pattern[i];
if (ch === "*") {
tokens.push({ kind: "star" });
}
else if (ch === "?") {
tokens.push({ kind: "one" });
}
else if (ch === "[") {
const bracket = parseBracketExpression(pattern, i);
if (bracket === undefined)
tokens.push({ kind: "text", text: "[" });
else {
const cls = fsGlobClass(bracket.source);
if (cls === undefined)
return undefined;
tokens.push({ kind: "class", class: cls });
i = bracket.end;
}
}
else {
tokens.push({ kind: "text", text: ch });
}
}
return compileFsGlob(tokens, "start");
}
function parseBracketExpression(pattern, start) {
let i = start + 1;
let negate = false;
if (pattern[i] === "!" || pattern[i] === "^") {
negate = true;
i++;
}
const contentStart = i;
let body = "";
let anyChar = false;
for (; i < pattern.length; i++) {
const ch = pattern[i];
if (ch === "]" && i > contentStart) {
if (body.length === 0 && !anyChar)
return undefined;
return { source: anyChar ? "[^/]" : `[${negate ? "^" : ""}${body}]`, end: i };
}
if (ch === "[" && (pattern[i + 1] === ":" || pattern[i + 1] === "." || pattern[i + 1] === "=")) {
anyChar = true;
const close = pattern.indexOf(`${pattern[i + 1]}]`, i + 2);
if (close >= 0 && (pattern[i + 1] === ":" ? /^[A-Za-z]+$/.test(pattern.slice(i + 2, close)) : close === i + 3))
i = close + 1;
continue;
}
body += ch === "-" ? "-" : ch.replace(/[\]\\^]/g, "\\$&");
}
return undefined;
}
function globSegmentMatches(re, pattern, name) {
if (name.startsWith(".") && !pattern.startsWith("."))
return false;
return re.test(name);
}
function pathSegmentsFrom(p, from, posix = false) {
const segs = [];
const isSep = (c) => c === "/" || (!posix && c === "\\");
let scan = from;
while (scan < p.length) {
while (scan < p.length && isSep(p[scan]))
scan++;
const s = scan;
while (scan < p.length && !isSep(p[scan]))
scan++;
if (scan > s)
segs.push({ text: p.slice(s, scan), start: s });
}
return segs;
}
function basesFor(candidate, boundary) {
if (candidate.bases === "unmodelled")
return "unmodelled";
const bases = candidate.bases.length > 0 ? candidate.bases : [boundary.cwd ?? boundary.roots[0] ?? ""];
return candidate.repositoryTop !== undefined ? everyAncestor(bases) : bases;
}
const UNPLACED_WHY = { moved_through_own_cwd: "is read from a directory the command moved to through its own working directory link (/proc/self/cwd), which is not placed here", below_own_link: "goes on below a link of the program that reads it (a descriptor, /proc/self/fd/<n> or /dev/fd/<n>, or a thread's working directory, root or descriptor under /proc/self/task/<tid>), which leads wherever that program holds it: where it lands is not placed here" };
function placeOperand(base, spelled, homeDir, walks = false) {
const ownBase = base === "" ? undefined : ownProcessSpelling(base);
if (ownBase?.startsWith(".") === true)
return { unplaced: "moved_through_own_cwd", views: [resolveOperandSpellings(base, spelled, homeDir)?.folded ?? base] };
const at = (ownBase ?? base) === "" ? undefined : (ownBase ?? base);
const word = resolveOperandSpellings(at, spelled, homeDir);
const own = word === undefined ? undefined : ownProcessSpelling(word.spelled ?? word.folded);
const placed = own === undefined ? word : resolveOperandSpellings(at, own, homeDir);
if (placed !== undefined && belowOwnProcessLink(placed.spelled ?? placed.folded, walks))
return { unplaced: "below_own_link", views: [...new Set([placed.folded, ...(own !== undefined ? [word.folded] : [])])] };
return placed === undefined ? undefined : { word: placed, ...(own !== undefined ? { asWritten: word.folded } : {}) };
}
function placedSpellings(spelled, bases, homeDir) {
const out = [];
for (const [base, word] of bases.flatMap((b) => readingsAt(b, spelled))) {
const at = placeOperand(base, word, homeDir);
if (at === undefined || "unplaced" in at)
continue;
out.push(at.word.folded);
if (at.word.spelled !== undefined)
out.push(at.word.spelled);
}
return out;
}
function lexicalReadsOf(candidate, boundary, placed) {
const rewritten = candidate.expands === "unresolvable" ? `"${candidate.raw}" is rewritten by the shell before the program sees it` : undefined;
const bases = placed ?? basesFor(candidate, boundary);
if (bases === "unmodelled") {
const floorsAt = candidate.floorBases ?? [boundary.cwd ?? boundary.roots[0] ?? ""];
const spellings = [candidate.spelled, ...placedSpellings(candidate.spelled, floorsAt.filter((f) => f !== ""), boundary.homeDir)];
const anywhereAbove = candidate.repositoryTop !== undefined || candidate.unsettledStart === true;
const ancestorViews = anywhereAbove ? [...new Set(placedSpellings(candidate.spelled, everyAncestor(floorsAt.filter((f) => f !== "")), boundary.homeDir))].filter((v) => !spellings.includes(v)) : [];
return [{ candidate, established: "unestablishable", spellings, ...(ancestorViews.length > 0 ? { ancestorViews } : {}), cause: rewritten ?? `"${candidate.raw}" is relative to a working directory this command's text does not settle` }];
}
if (rewritten !== undefined)
return [{ candidate, established: "unestablishable", spellings: [...new Set([candidate.spelled, ...placedSpellings(candidate.spelled, bases, boundary.homeDir)])], cause: rewritten }];
const accountHome = candidate.face !== "write" && tildeNamesAnAccount(candidate.spelled) ? { unresolved: true } : {};
const out = [];
const seen = new Set();
for (const [base, word] of bases.flatMap((b) => readingsAt(b, candidate.spelled))) {
const at = placeOperand(base, word, boundary.homeDir, candidate.provenance === "traversal_root");
const why = at !== undefined && "unplaced" in at ? at : undefined;
const placed = at !== undefined && !("unplaced" in at) ? at : undefined;
if (placed === undefined || placed.word.standIn === true) {
const key = `?${candidate.spelled}`;
if (!seen.has(key)) {
seen.add(key);
out.push({ candidate, established: "unestablishable", spellings: [...new Set([candidate.spelled, ...(why?.views ?? [])])], cause: why !== undefined ? `"${candidate.raw}" ${UNPLACED_WHY[why.unplaced]}` : `"${candidate.raw}" cannot be placed against ${base === "" ? "no working directory" : `"${base}"`}`, ...accountHome });
}
if (placed === undefined)
continue;
}
const sp = placed.word;
if (seen.has(sp.folded))
continue;
seen.add(sp.folded);
out.push({ candidate, established: "lexical", target: sp.folded, spellings: sp.spelled !== undefined ? [sp.folded, sp.spelled] : [sp.folded], ...(placed.asWritten !== undefined ? { ancestorViews: [placed.asWritten] } : {}) });
}
return out;
}
function writtenByText(plan, boundary) {
const targets = new Set();
const runs = [];
const writes = [];
let concurrent = false;
const speculativeSeen = new Set();
let unplaced = false;
const walk = (p) => {
for (const s of p.segments) {
for (const n of s.nested)
walk(n);
const wrote = [];
runs.push(s);
writes.push(wrote);
if (p.shape.backgrounded || s.connector === "|")
concurrent = true;
for (const c of s.reads) {
if (c.speculative === undefined || c.expands !== false || c.bases === "unmodelled")
continue;
for (const r of lexicalReadsOf(c, boundary)) {
if (r.target === undefined)
continue;
const t = normalizeAbsPathLexically(r.target);
if (speculativeSeen.has(t))
targets.add(t);
speculativeSeen.add(t);
}
}
for (const j of judgedCandidatesOf(s)) {
if (j.candidate.face !== "write" || j.onlyIf !== undefined)
continue;
if (j.candidate.expands !== false || j.candidate.bases === "unmodelled") {
unplaced = true;
continue;
}
for (const r of lexicalReadsOf(j.candidate, boundary)) {
if (r.target === undefined)
unplaced = true;
else {
const t = normalizeAbsPathLexically(r.target);
targets.add(t);
wrote.push(t);
}
}
}
}
};
walk(plan);
return { targets, unplaced, runs, writes, concurrent };
}
export function writtenOnLineBefore(writes, at, concurrent, place) {
const fold = (p) => p.normalize("NFC").toLowerCase();
const here = fold(place);
return writes.some((paths, i) => i !== at && (i < at || concurrent) && paths.some((w) => withinAnyRoot([fold(w)], here) || withinAnyRoot([here], fold(w))));
}
function unfollowedBackupReads(j, boundary, cause) {
const named = sedBackupNames(j.followed.operand.spelled, j.followed.suffix).flatMap((name) => lexicalReadsOf({ ...j.candidate, spelled: name }, boundary));
const spellings = named.flatMap((r) => [...(r.target !== undefined ? [r.target] : []), ...r.spellings]);
const ancestorViews = [...new Set(named.flatMap((r) => r.ancestorViews ?? []))];
const read = { candidate: j.candidate, established: "unestablishable", spellings: [...new Set(spellings)], ...(ancestorViews.length > 0 ? { ancestorViews } : {}), cause };
return (j.seats ?? ["landing"]).map((seat) => writtenAt(read, j, seat));
}
function writtenAt(read, j, seat) {
if (read.candidate.face !== "write" || !(j.written ?? j.seats ?? ["landing"]).includes(seat))
return read;
return { ...read, written: { seat, ...(j.child === true ? { child: true } : {}) } };
}
export function establishShellReadsLexically(plan, boundary) {
const reads = new Map();
const nested = new Map();
for (const segment of plan.segments) {
reads.set(segment, judgedCandidatesOf(segment).flatMap((j) => {
if (j.followed !== undefined)
return unfollowedBackupReads({ ...j, followed: j.followed }, boundary, `"${j.followed.operand.raw}" names its backup through a link chain only the filesystem can follow`);
const seat = (j.written ?? j.seats ?? ["landing"]).includes("landing") ? "landing" : "entry";
return lexicalReadsOf(j.candidate, boundary).map((r) => writtenAt(r, j, seat));
}));
for (const n of segment.nested)
nested.set(n, establishShellReadsLexically(n, boundary));
}
return { plan, reads, nested, roots: boundary.roots };
}
export function createShellReadEstablisher(env, readRoots, opts) {
const lexicalOnly = boundaryIsTheSandbox(env);
const canonicalRoots = canonicalRootsOnce(env, readRoots, opts?.rootsCanonical === true);
const legOver = (seen) => establishLegOver(seen, readRoots);
return {
lexicalOnly,
establish: async (plan, boundary, signal, door = observeEnvironment(env)) => {
if (lexicalOnly)
return establishShellReadsLexically(plan, boundary);
const { roots, incomplete } = await canonicalRoots(signal);
door.adopt(incomplete);
return await withHomeViews(door, opts, await legOver(door)(plan, { ...boundary, roots }, roots, signal), signal);
},
reestablish: async (previous, boundary, signal) => {
if (lexicalOnly)
return { changed: [] };
const again = await legOver(observeEnvironment(env))(previous.plan, { ...boundary, roots: previous.roots }, previous.roots, signal);
return { changed: movedReads(previous, again) };
},
};
}
function establishLegOver(seen, readRoots) {
const env = seen.fs;
const resolverIsAuthoritative = seen.authoritative;
const bounded = (detail) => (seen.bound(detail), { unverifiable: detail });
const family = pathFamilyOf({ root: readRoots[0] ?? "/" });
const SEP = family === "posix" ? /\// : /[\\/]/;
const TRAILING_SEP = family === "posix" ? /\/+$/ : /[\\/]+$/;
const joinUnder = (dir, name) => `${dir.replace(TRAILING_SEP, "")}/${name}`;
const rootPartsOf = (parts) => {
if (family !== "win" || parts[0] !== "" || parts[1] !== "")
return 1;
for (let i = 2, named = 0; i < parts.length; i++)
if (parts[i] !== "" && ++named === 2)
return i + 1;
return undefined;
};
const placeOfParts = (parts, n, r) => n > r ? parts.slice(0, n).join("/") : r === 1 && family === "win" && isAbsoluteForFamily("win", `${parts[0]}/`) ? `${parts[0]}/` : parts.slice(0, r).join("/") || "/";
const tops = new Map();
const atRepositoryTops = async (starts, signal) => {
const out = new Set();
for (const start of starts) {
if (!tops.has(start))
tops.set(start, repositoryTopOf(env, start, family, signal));
const top = await tops.get(start);
for (const b of top !== undefined ? [top] : everyAncestor([start]))
out.add(b);
}
return [...out];
};
const resolveWithoutParentSteps = async (p, signal, writeTarget = false, linkHops = WRITE_LINK_HOPS, climbs) => {
const parts = p.split(SEP);
const root = rootPartsOf(parts);
if (root === undefined)
return undefined;
const tail = [];
let allAbsent = true;
while (parts.length >= root) {
const at = placeOfParts(parts, parts.length, root);
const canon = await env.canonicalPath(at, signal);
if (!canon.ok && canon.error.code === "not_found" && writeTarget && allAbsent) {
const entry = await env.fileInfo(at, signal);
const link = entry.ok && entry.value.kind === "symlink" ? (linkHops > 0 ? await env.readLink?.(at, signal) : void bounded(`"${at}" is a link chain of more than ${WRITE_LINK_HOPS} links, too many to follow to verify where it lands`)) : undefined;
if (link?.ok === true) {
const landing = anchorSpelling(family, placeOfParts(parts, parts.length - 1, root), link.value);
return await resolve([landing, ...[...tail].reverse()].join("/"), signal, true, linkHops - 1, climbs);
}
if (entry.ok || entry.error.code !== "not_found")
allAbsent = false;
}
if (canon.ok) {
if (tail.length === 0)
return { value: canon.value, exact: true };
return { value: [canon.value.replace(TRAILING_SEP, ""), ...[...tail].reverse()].join("/"), exact: false, missing: allAbsent };
}
if (!isAbsence(canon.error.code))
allAbsent = false;
tail.push(parts.pop());
}
return undefined;
};
const parentOf = (canonical) => normalizeAbsPathLexically(`${canonical}/..`);
const resolve = async (p, signal, writeTarget = false, linkHops = WRITE_LINK_HOPS, climbs) => {
if (ownProcessSpelling(p)?.startsWith(".") === true || belowOwnProcessLink(p))
return { value: p, exact: false };
const parts = p.split(SEP);
const first = parts.findIndex((seg) => seg === "..");
if (first < 0)
return await resolveWithoutParentSteps(p, signal, writeTarget, linkHops, climbs);
const headEnd = parts.slice(0, first).reduce((n, seg) => n + seg.length + 1, 0);
let head = await resolveWithoutParentSteps(p.slice(0, headEnd) || "/", signal, writeTarget, linkHops, climbs);
if (head === undefined)
return undefined;
let pending = [];
const flush = async () => {
if (pending.length === 0)
return true;
const next = await resolveWithoutParentSteps([head.value.replace(TRAILING_SEP, ""), ...pending].join("/"), signal, writeTarget, linkHops, climbs);
pending = [];
if (next === undefined)
return false;
head = next;
return true;
};
let climbing = false;
for (let i = first; i < parts.length; i++) {
const seg = parts[i];
if (seg === "" || seg === ".")
continue;
if (seg !== "..") {
pending.push(seg);
climbing = false;
continue;
}
if (!(await flush()))
return undefined;
if (!head.exact)
return head;
if (climbs !== undefined && !climbing)
climbing = noteClimb(family, head.value, parts.slice(i + 1), climbs);
head = { value: parentOf(head.value), exact: true };
}
return (await flush()) ? head : undefined;
};
const climbWalk = (signal) => (p, climbs) => resolve(p, signal, false, WRITE_LINK_HOPS, climbs);
const literalRootHead = (p, roots) => {
let best;
for (const r of [...readRoots, ...roots]) {
if (!r)
continue;
const withSep = r.endsWith("/") || r.endsWith("\\") ? r : `${r}/`;
if (p !== r && !p.startsWith(withSep))
continue;
if (best === undefined || r.length > best.length)
best = r;
}
return best;
};
const expandGlobCandidate = async (p, roots, signal) => {
const head = literalRootHead(p, roots);
let segs = pathSegmentsFrom(p, head?.length ?? 0, family === "posix");
let first = segs.findIndex((s) => GLOB_METACHAR_RE.test(s.text));
if (first < 0 && head !== undefined && GLOB_METACHAR_RE.test(head)) {
segs = pathSegmentsFrom(p, 0, family === "posix");
first = segs.findIndex((s) => GLOB_METACHAR_RE.test(s.text));
}
if (first < 0)
return undefined;
let frontier = [p.slice(0, segs[first].start).replace(TRAILING_SEP, "") || "/"];
let dirsUsed = 0;
let matches = 0;
const canonicalOfMatch = new Map();
for (let j = first; j < segs.length; j++) {
const seg = segs[j].text;
if (!GLOB_METACHAR_RE.test(seg)) {
frontier = frontier.map((d) => joinUnder(d, seg));
continue;
}
const re = compileGlobSegment(seg);
if (re === undefined)
return { unverifiable: `the pattern "${seg}" cannot be expanded to verify what it would read` };
const isLast = j === segs.length - 1;
const next = [];
for (const dir of frontier) {
if (++dirsUsed > MAX_GLOB_DIRS)
return bounded(`"${p}" expands over more than ${MAX_GLOB_DIRS} directories, too many to enumerate to verify`);
if (belowOwnProcessLink(dir, true))
return { unverifiable: `"${dir}" is a link of the program that reads it (or below one), so what "${seg}" would expand to cannot be verified here` };
const canonDir = await resolve(dir, signal);
if (canonDir !== undefined && canonDir.missing === true)
continue;
if (canonDir !== undefined && !canonDir.exact)
return { unverifiable: `"${dir}" cannot be resolved to verify what "${seg}" would expand to`, unresolved: true };
const listed = await env.listDir(canonDir?.value ?? dir, signal);
if (!listed.ok) {
if (isAbsence(listed.error.code))
continue;
return { unverifiable: `"${dir}" cannot be enumerated to verify what "${seg}" would expand to (${listed.error.code})`, unresolved: true };
}
if (seg.startsWith(".")) {
for (const dot of [".", ".."])
if (re.test(dot))
next.push(joinUnder(dir, dot));
}
const canonDirHere = isLast ? canonDir?.value : undefined;
for (const entry of listed.value) {
if (!globSegmentMatches(re, seg, entry.name))
continue;
if (++matches > MAX_GLOB_MATCHES)
return bounded(`"${p}" expands to more than ${MAX_GLOB_MATCHES} names, too many to enumerate to verify`);
const candidate = joinUnder(dir, entry.name);
if (canonDirHere !== undefined && entry.kind !== "symlink")
canonicalOfMatch.set(candidate, joinUnder(canonDirHere, entry.name));
next.push(candidate);
}
}
frontier = next;
if (frontier.length === 0)
return { paths: [], canonical: canonicalOfMatch };
}
return { paths: frontier, canonical: canonicalOfMatch };
};
const rootKindOf = async (rootCanonical, signal) => {
const info = await env.fileInfo(rootCanonical, signal);
if (!info.ok)
return undefined;
return info.value.kind === "directory" ? "directory" : info.value.kind === "file" ? "file" : undefined;
};
const entryOf = async (spelling, signal, climbs) => {
const parts = spelling.split(SEP);
const root = rootPartsOf(parts);
const leaf = parts.pop() ?? "";
if (leaf === "" || leaf === "." || leaf === ".." || root === undefined || parts.length < root)
return await resolve(spelling, signal, true, WRITE_LINK_HOPS, climbs);
const up = climbs === undefined ? undefined : [];
const parent = await resolve(placeOfParts(parts, parts.length, root), signal, true, WRITE_LINK_HOPS, up);
for (const landing of up ?? [])
if (!climbs.includes(joinUnder(landing, leaf)))
climbs.push(joinUnder(landing, leaf));
if (parent === undefined)
return undefined;
return { value: joinUnder(parent.value, leaf), exact: parent.exact, ...(parent.missing !== undefined ? { missing: parent.missing } : {}) };
};
const takenAsSpelled = (candidate, spelling, spellings, origin) => ({
candidate,
established: "lexical",
target: normalizeAbsPathLexically(spelling),
spellings,
...(origin !== undefined ? { origin } : {}),
});
const canonicalReadOf = async (candidate, spelling, spellings, established, origin, canonicalKnown, signal, seat = "landing", climbs) => {
const unplacedOwnLink = belowOwnProcessLink(spelling, candidate.provenance === "traversal_root");
if (isBareOwnDescriptorLink(spelling) && !unplacedOwnLink)
return takenAsSpelled(candidate, spelling, spellings, origin);
const real = canonicalKnown !== undefined ? { value: canonicalKnown, exact: true } : unplacedOwnLink ? { value: spelling, exact: false } : seat === "entry" ? await entryOf(spelling, signal, climbs) : await resolve(spelling, signal, candidate.face === "write", WRITE_LINK_HOPS, climbs);
if (real === undefined) {
if (resolverIsAuthoritative)
return { candidate, established: "unestablishable", spellings, ...(origin !== undefined ? { origin } : {}), cause: `"${spelling}" cannot be resolved to verify where it reads`, unresolved: true };
return takenAsSpelled(candidate, spelling, spellings, origin);
}
if (!real.exact && real.missing !== true) {
return { candidate, established: "unestablishable", spellings, ...(origin !== undefined ? { origin } : {}), cause: `"${spelling}" cannot be resolved to verify where it reads`, unresolved: true };
}
const hops = seat === "landing" && leafChainMayHold([spelling], !real.exact || real.value !== normalizeAbsPathLexically(spelling), family) ? chainHopsOrNone(await symlinkChainHops(env, spelling, signal, family)) : [];
return { candidate, established, target: real.value, spellings, ...(origin !== undefined ? { origin } : {}), ...(hops.length > 0 ? { hops } : {}) };
};
const followedName = async (spelled, base, homeDir, signal) => {
let name = spelled;
for (let hop = 0; hop <= WRITE_LINK_HOPS; hop++) {
const placed = placeOperand(base, name, homeDir);
if (placed === undefined || "unplaced" in placed || placed.word.standIn === true)
return undefined;
const walked = placed.word.spelled ?? placed.word.folded;
if (TRAILING_SEP.test(walked))
return name;
const parts = walked.split(SEP);
const root = rootPartsOf(parts);
const leaf = parts.pop() ?? "";
if (leaf === "" || leaf === "." || leaf === ".." || root === undefined || parts.length < root)
return name;
const parent = await resolve(placeOfParts(parts, parts.length, root), signal);
if (parent === undefined)
return undefined;
if (!parent.exact)
return parent.missing === true ? name : undefined;
const entry = await env.fileInfo(joinUnder(parent.value, leaf), signal);
if (!entry.ok)
return isAbsence(entry.error.code) ? name : undefined;
if (entry.value.kind !== "symlink")
return name;
const link = await env.readLink?.(joinUnder(parent.value, leaf), signal);
if (link?.ok !== true)
return undefined;
const dir = name.slice(0, name.search(/[^/]*$/));
name = dir === "" ? link.value : anchorSpelling(family, dir, link.value);
}
return void bounded(`"${spelled}" is a link chain of more than ${WRITE_LINK_HOPS} links, too many to follow to verify where its backup is written`);
};
const followedBackupReads = async (j, boundary, signal) => {
const { operand, suffix } = j.followed;
const bases = basesFor(operand, boundary);
const unfollowed = (cause) => unfollowedBackupReads(j, boundary, cause);
if (bases === "unmodelled")
return unfollowed(`"${operand.raw}" is relative to a working directory this command's text does not settle`);
const out = [];
for (const base of bases) {
const name = await followedName(operand.spelled, base, boundary.homeDir, signal);
if (name === undefined) {
out.push(...unfollowed(`"${operand.raw}" names its backup through a link chain that could not be read`));
continue;
}
for (const backup of sedBackupNames(name, suffix)) {
const placed = placeOperand(base, backup, boundary.homeDir);
if (placed === undefined || "unplaced" in placed || placed.word.standIn === true) {
out.push(...unfollowed(`"${backup}" cannot be placed against "${base}"`));
continue;
}
const at = placed.word;
const spellings = at.spelled !== undefined ? [at.folded, at.spelled] : [at.folded];
const derived = name !== operand.spelled ? { derivedSpellings: spellings } : {};
for (const seat of j.seats ?? ["landing"])
out.push(writtenAt({ ...(await canonicalReadOf(j.candidate, at.spelled ?? at.folded, spellings, "canonical", undefined, undefined, signal, seat)), ...derived }, j, seat));
}
}
return out;
};
const confirmedMissing = async (candidate, boundary, signal) => {
if (candidate.expands !== false)
return false;
const reads = lexicalReadsOf(candidate, boundary);
if (reads.length === 0)
return false;
for (const r of reads) {
if (r.established !== "lexical" || r.target === undefined)
return false;
const real = await resolve(r.target, signal);
if (real === undefined || real.exact || real.missing !== true)
return false;
}
return true;
};
const factOf = async (fact, segment, written, boundary, signal) => {
if (fact.holds === "present")
return (await confirmedMissing(fact.candidate, boundary, signal)) ? false : undefined;
if (fact.candidate.expands !== false || written.unplaced)
return undefined;
let directory;
for (const r of lexicalReadsOf(fact.candidate, boundary)) {
if (r.established !== "lexical" || r.target === undefined)
return undefined;
if (writtenOnLineBefore(written.writes, written.runs.indexOf(segment), written.concurrent, normalizeAbsPathLexically(r.target)))
return undefined;
const at = fact.seat === "entry" ? await entryOf(r.target, signal) : await resolve(r.target, signal);
if (at === undefined || (!at.exact && at.missing !== true))
return undefined;
const info = at.missing === true && !at.exact ? undefined : fact.seat === "entry" ? await env.fileInfo(at.value, signal) : await env.listDir(at.value, signal);
const here = info === undefined ? false : info.ok ? Array.isArray(info.value) || info.value.kind === "directory" : isAbsence(info.error.code) ? false : undefined;
if (here === undefined || (directory !== undefined && directory !== here))
return undefined;
directory = here;
}
return directory === undefined ? undefined : directory === (fact.holds === "directory");
};
const establishSegment = async (segment, boundary, roots, written, signal) => {
const out = [];
const missing = new Map();
const facts = new Map();
for (const listed of judgedCandidatesOf(segment)) {
let judged = listed;
const speculative = judged.candidate.speculative;
if (speculative !== undefined && !written.unplaced) {
const c = judged.candidate;
if (!missing.has(c))
missing.set(c, (await confirmedMissing(c, boundary, signal)) && !lexicalReadsOf(c, boundary).some((r) => r.target !== undefined && written.targets.has(normalizeAbsPathLexically(r.target))));
if (missing.get(c) === true) {
if (speculative === "whole")
continue;
judged = { ...judged, candidate: { ...c, denyOnly: true } };
}
}
const decides = judged.onlyIf;
if (decides !== undefined) {
const key = `${decides.holds}:${decides.seat ?? "landing"}`;
const seen = facts.get(decides.candidate) ?? new Map();
facts.set(decides.candidate, seen);
if (!seen.has(key))
seen.set(key, await factOf(decides, segment, written, boundary, signal));
if (seen.get(key) === false)
continue;
}
if (judged.followed !== undefined) {
out.push(...(await followedBackupReads({ ...judged, followed: judged.followed }, boundary, signal)));
continue;
}
const candidate = judged.candidate;
const traversal = candidate.provenance === "traversal_root";
const resolvesItself = TRAILING_SEP.test(candidate.spelled) || [".", ".."].includes(candidate.spelled.split(SEP).pop() ?? "");
const landsToo = (ss) => (resolvesItself && ss.length > 0 && !ss.includes("landing") ? [...ss, "landing"] : ss);
const seats = judged.seats === undefined ? ["landing"] : landsToo(judged.seats);
const writtenSeats = { ...judged, written: judged.written === undefined ? seats : landsToo(judged.written) };
const atSeats = async (spelling, spellings, established, origin, canonicalKnown) => {
const reads = [];
const keep = (read, climbed = false) => {
const same = reads.findIndex((r) => r.established === read.established && r.target === read.target);
if (same < 0)
return void reads.push(read);
const [kept, other] = reads[same].written === undefined && read.written !== undefined ? [read, reads[same]] : [reads[same], read];
reads[same] = climbed ? withClimbedViews(kept, other) : kept;
};
for (const seat of seats) {
const climbs = [];
keep(writtenAt(await canonicalReadOf(candidate, spelling, spellings, established, origin, canonicalKnown, signal, seat, climbs), writtenSeats, seat));
await landingsOf(climbs, async (landing) => keep(writtenAt(await canonicalReadOf(candidate, landing, [landing, ...spellings], established, origin, undefined, signal, seat, climbs), writtenSeats, seat), true), bounded);
}
return reads;
};
const land = async (read) => {
if (!traversal || (read.established !== "canonical" && read.established !== "expansion") || read.target === undefined) {
out.push(read);
return;
}
const node = await rootKindOf(read.target, signal);
out.push({ ...read, ...(node !== undefined ? { node } : {}) });
};
const placed = candidate.repositoryTop === "discovered" && candidate.bases !== "unmodelled" && candidate.bases.length > 0 ? await atRepositoryTops(candidate.bases, signal) : undefined;
for (const [i, lexical] of lexicalReadsOf(candidate, boundary, placed).entries()) {
if (lexical.established !== "lexical" || passesUnasked(candidate)) {
out.push(writtenAt(await withFloorClimbs(family, lexical, climbWalk(signal), bounded, signal), writtenSeats, writtenSeats.written.includes("landing") ? "landing" : "entry"));
continue;
}
try {
const folded = lexical.target;
const spellings = lexical.spellings;
const walked = spellings.find((s) => s !== folded) ?? folded;
const viewed = (r) => (lexical.ancestorViews === undefined ? r : { ...r, ancestorViews: lexical.ancestorViews });
if (candidate.expands === "glob") {
let matched = false;
for (const p of await withClimbedPatterns(family, candidate.pattern === undefined ? spellings : lexicalReadsOf({ ...candidate, spelled: candidate.pattern }, boundary, placed)[i]?.spellings ?? spellings, climbWalk(signal), bounded, signal)) {
const expanded = await expandGlobCandidate(p, roots, signal);
if (expanded !== undefined && "unverifiable" in expanded) {
out.push(viewed({ candidate, established: "unestablishable", spellings, origin: folded, cause: expanded.unverifiable, ...(expanded.unresolved === true ? { unresolved: true } : {}) }));
matched = true;
continue;
}
if (expanded !== undefined && expanded.paths.length > 0) {
matched = true;
for (const t of expanded.paths)
for (const read of await atSeats(t, [t, folded], "expansion", folded, expanded.canonical.get(t)))
await land(viewed(read));
}
}
if (!matched || candidate.pattern !== undefined)
for (const read of await atSeats(walked, spellings, "canonical", undefined, undefined))
await land(viewed(read));
continue;
}
for (const read of await atSeats(walked, spellings, "canonical", undefined, undefined))
await land(viewed(read));
}
catch (e) {
if (resolveOperandSpellings(readRoots[0], candidate.spelled, boundary.homeDir)?.standIn !== true || signal?.aborted === true)
throw e;
}
}
}
return out;
};
const establishPlan = async (plan, boundary, roots, signal, written = writtenByText(plan, boundary)) => {
const reads = new Map();
const nested = new Map();
for (const segment of plan.segments) {
reads.set(segment, await establishSegment(segment, boundary, roots, written, signal));
for (const n of segment.nested)
nested.set(n, await establishPlan(n, boundary, roots, signal, written));
}
return { plan, reads, nested, roots };
};
return establishPlan;
}