@sema-agent/core
Version:
Stateless, task-oriented AI agent core
403 lines (402 loc) • 17.4 kB
JavaScript
import { lstatSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { err, FileError, ok } from "../../internal/harness.js";
import { performsIo } from "../remote-env.js";
import { thrownText } from "../thrown-value.js";
import { envErrorDetail } from "../../tools/fs/env-error-detail.js";
import { physicalPathOfExisting } from "../physical-path.js";
import { PROJECT_ID_REGEX } from "../project-seat.js";
function pathSegmentsDualFamily(p) {
return p.split(/[\\/]/).filter(Boolean);
}
const CASE_INSENSITIVE_FS = process.platform === "darwin" || process.platform === "win32";
const foldPathCase = (s) => (CASE_INSENSITIVE_FS ? s.toLowerCase() : s);
export const SCOPE_SEGMENT_MAX_ENCODED = 64;
const SEGMENT_SAFE = /^[A-Za-z0-9._-]$/;
export function encodeScopeSegment(raw) {
if (raw.length === 0)
throw new Error("scope segment must be non-empty");
if (!isWellFormedString(raw))
throw new Error("scope segment is not well-formed Unicode (lone surrogate)");
let out = "";
for (const ch of raw) {
if (SEGMENT_SAFE.test(ch)) {
out += ch;
}
else {
for (const byte of Buffer.from(ch, "utf8"))
out += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
}
}
if (out.length > SCOPE_SEGMENT_MAX_ENCODED) {
throw new Error(`scope segment exceeds ${SCOPE_SEGMENT_MAX_ENCODED} encoded chars (${out.length}): ${out.slice(0, 24)}…`);
}
return out;
}
function isWellFormedString(s) {
const anyS = s;
if (typeof anyS.isWellFormed === "function")
return anyS.isWellFormed();
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
if (c >= 0xd800 && c <= 0xdbff) {
const n = s.charCodeAt(i + 1);
if (!(n >= 0xdc00 && n <= 0xdfff))
return false;
i++;
}
else if (c >= 0xdc00 && c <= 0xdfff)
return false;
}
return true;
}
const FATAL_UTF8 = new TextDecoder("utf-8", { fatal: true });
function scopeKeyRefusal(message) {
const e = new Error(message);
e.code = "config.memory_scope_key";
return e;
}
export function decodeScopeSegment(encoded) {
if (encoded.length > SCOPE_SEGMENT_MAX_ENCODED) {
throw scopeKeyRefusal(`scope segment exceeds ${SCOPE_SEGMENT_MAX_ENCODED} encoded chars (${encoded.length})`);
}
if (!/^(?:[A-Za-z0-9._-]|%[0-9A-F]{2})*$/.test(encoded)) {
throw scopeKeyRefusal(`malformed scope segment: ${encoded}`);
}
const bytes = [];
for (let i = 0; i < encoded.length; i++) {
if (encoded[i] === "%") {
bytes.push(parseInt(encoded.slice(i + 1, i + 3), 16));
i += 2;
}
else {
bytes.push(encoded.charCodeAt(i));
}
}
let decoded;
try {
decoded = FATAL_UTF8.decode(Uint8Array.from(bytes));
}
catch {
throw scopeKeyRefusal(`malformed scope segment (invalid UTF-8 in %XX sequence): ${encoded}`);
}
let reencoded;
try {
reencoded = encodeScopeSegment(decoded);
}
catch (e) {
throw scopeKeyRefusal(`non-canonical scope segment (${thrownText(e)}): ${encoded}`);
}
if (reencoded !== encoded) {
throw scopeKeyRefusal(`non-canonical scope segment (re-encode mismatch): ${encoded}`);
}
return decoded;
}
export function formatUserScope(principal) {
return `user:${encodeScopeSegment(principal)}`;
}
export function formatUserLocalScope(principal) {
return `${USERLOCAL_PREFIX}${encodeScopeSegment(principal)}`;
}
export function formatOrgScope(tenant) {
return `org:${encodeScopeSegment(tenant)}`;
}
export function formatProjScope(tenant, projectId) {
return `proj:${encodeScopeSegment(tenant)}/${encodeScopeSegment(projectId)}`;
}
export function formatUserProjScope(principal, projectId) {
return `userproj:${encodeScopeSegment(principal)}/${encodeScopeSegment(projectId)}`;
}
const USERLOCAL_PREFIX = "userlocal:";
const ONE_SEGMENT = /^(user|userlocal|org):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
const TWO_SEGMENT = /^(proj|userproj):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)\/((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
const RESERVED_PREFIX = /^(user|userlocal|org|proj|userproj):/;
const foldedSpelling = (key) => String(key).trim().normalize("NFKC").toLowerCase();
function reservedPrefixOf(key) {
const exact = RESERVED_PREFIX.exec(key);
if (exact)
return { kind: exact[1], exact: true };
const folded = RESERVED_PREFIX.exec(foldedSpelling(key));
return folded ? { kind: folded[1], exact: false } : undefined;
}
export function parseScopeKey(key) {
const m1 = ONE_SEGMENT.exec(key);
if (m1) {
const seg = decodeScopeSegment(m1[2]);
return m1[1] === "org" ? { kind: "org", tenant: seg } : { kind: m1[1], principal: seg };
}
const m2 = TWO_SEGMENT.exec(key);
if (m2) {
const a = decodeScopeSegment(m2[2]);
const b = decodeScopeSegment(m2[3]);
return m2[1] === "proj" ? { kind: "proj", tenant: a, projectId: b } : { kind: "userproj", principal: a, projectId: b };
}
const reserved = reservedPrefixOf(key);
if (reserved) {
throw scopeKeyRefusal(`malformed v2 scope key "${key}": prefix "${reserved.kind}:" is reserved by the scope contract ` +
`— ${reserved.exact ? "" : "the key spells it with another case, a full-width colon or surrounding whitespace; the prefix is matched exactly, never folded to its kind — "}` +
`segments must be encoded with encodeScopeSegment (charset [A-Za-z0-9._-] + %XX), ` +
`"${reserved.kind}" takes ${reserved.kind === "proj" || reserved.kind === "userproj" ? "two segments (a/b)" : "one segment"}.`);
}
return { kind: "legacy", raw: key };
}
export function isOrgScopeKey(key) {
try {
return parseScopeKey(key).kind === "org";
}
catch {
return false;
}
}
export function isPersonalScope(parsed) {
return parsed.kind === "user" || parsed.kind === "userlocal" || parsed.kind === "userproj";
}
export function isPersonalPlaneScope(parsed) {
return isPersonalScope(parsed) || parsed.kind === "org";
}
export function memoryScopeOwnerOf(scope, scopeContract) {
if (scopeContract !== "v2")
return { kind: "deployment" };
const parsed = parseScopeKey(scope);
switch (parsed.kind) {
case "user":
case "userlocal":
case "userproj":
return { kind: "principal", principal: parsed.principal };
case "org":
case "proj":
return { kind: "tenant", tenant: parsed.tenant };
case "legacy":
return { kind: "deployment" };
default: {
const unhandled = parsed;
return unhandled;
}
}
}
export function isReplicableScope(key) {
if (typeof key !== "string")
throw new TypeError(`isReplicableScope: a scope key is a string (got ${key === null ? "null" : typeof key})`);
return reservedPrefixOf(key)?.kind !== "userlocal";
}
export function assertScopeContractPlacement(args) {
if (!args.repoRoot)
return;
const personal = args.parsedScopes.filter(isPersonalPlaneScope);
if (personal.length === 0)
return;
const rootSegs = pathSegmentsDualFamily(physicalPathOfExisting(resolve(args.repoRoot))).map(foldPathCase);
const dirSegs = pathSegmentsDualFamily(physicalPathOfExisting(resolve(args.memoryDir))).map(foldPathCase);
if (rootSegs.length <= dirSegs.length && rootSegs.every((s, i) => s === dirSegs[i])) {
const e = new Error(`memory scope contract v2: personal-plane scope(s) ${personal
.map((p) => `"${p.kind}"`)
.join(", ")} cannot materialize into an IN-REPO memory dir (${args.memoryDir}) — ` +
`a user/userlocal/userproj/org layer projected under the repo root would leak non-repo memory to every ` +
`collaborator (and into commit history). Move the memory dir out of the repo, or drop those scopes.`);
e.code = "config.memory_scope_placement";
throw e;
}
}
export const PROJECT_MARKER_PATH = ".sema/project";
export { PROJECT_ID_REGEX };
const UUID_RE = PROJECT_ID_REGEX;
export function normalizeProjectId(projectId) {
return projectId.toLowerCase();
}
export function formatProjectMarker(projectId) {
if (!UUID_RE.test(projectId))
throw new Error(`projectId must be a UUID, got: ${projectId}`);
return `projectId = ${normalizeProjectId(projectId)}\n`;
}
export const PROJECT_IDENTITY_REFUSAL_KINDS = Object.freeze([
"mismatch",
"marker_unreadable",
"write_project_mismatch",
"write_without_verdict",
]);
export const PROJECT_MARKER_UNREADABLE_REASONS = Object.freeze([
"io_error",
"unparseable",
"not_uuid",
"nested",
"repo_root_unreadable",
]);
const CORRUPT_MARKER_REASON = new WeakMap();
export function parseProjectMarker(body) {
const corrupt = (detail, reason) => {
const e = new Error(`corrupt project marker: ${detail}`);
e.code = "config.memory_project_marker";
CORRUPT_MARKER_REASON.set(e, reason);
throw e;
};
let projectId;
for (const line of body.split(/\r?\n/)) {
const t = line.trim();
if (!t || t.startsWith("#"))
continue;
if (!/^projectId\b/.test(t))
continue;
const m = /^projectId\s*=\s*(?:"([^"]*)"|([^"\s]+))\s*$/.exec(t);
if (!m)
corrupt(`unparseable projectId line (${t.slice(0, 48)})`, "unparseable");
const value = m[1] ?? m[2] ?? "";
if (!UUID_RE.test(value))
corrupt(`projectId is not a UUID (${value.slice(0, 48) || "<empty>"})`, "not_uuid");
const norm = normalizeProjectId(value);
if (projectId !== undefined && projectId !== norm)
corrupt("duplicate conflicting projectId lines", "unparseable");
projectId = norm;
}
if (projectId === undefined)
return null;
return { projectId };
}
export const hostProjectMarkerFs = {
exists(path) {
try {
return Promise.resolve(ok(lstatSync(path, { throwIfNoEntry: false }) !== undefined));
}
catch (e) {
const code = e.code;
return Promise.resolve(code === "ENOTDIR" ? ok(false) : err(new FileError("unknown", `could not stat ${path}: ${thrownText(e)}`, path)));
}
},
readTextFile(path) {
try {
return Promise.resolve(ok(readFileSync(path, "utf8")));
}
catch (e) {
return Promise.resolve(err(new FileError("unknown", `could not read ${path}: ${thrownText(e)}`, path)));
}
},
};
export function projectMarkerFsOf(env) {
return performsIo(env) === false ? hostProjectMarkerFs : env;
}
function identityError(code, message, detail) {
const e = new Error(message);
e.code = code;
if (detail !== undefined)
e.detail = detail;
return e;
}
function markerUnreadable(taskDir, markerDir, reason) {
return markerDir === taskDir ? { kind: "marker_unreadable", markerPath: join(markerDir, PROJECT_MARKER_PATH), reason } : { kind: "marker_unreadable", reason };
}
async function readOrFault(path, read, detail) {
let r;
try {
r = await read();
}
catch (e) {
r = { ok: false, error: { message: thrownText(e) } };
}
if (!r.ok)
throw identityError("config.memory_project_marker", `project marker lookup could not read ${path}: ${envErrorDetail(r.error.message)}`, detail);
return r.value;
}
const existsOrFault = (fs, path, detail) => readOrFault(path, () => fs.exists(path), detail);
function isMarkerFault(e) {
const code = e instanceof Error ? e.code : undefined;
return code === "config.memory_project_marker" || code === "config.memory_project_marker_nested";
}
async function gitRootOf(fs, dir) {
let cur = resolve(dir);
for (;;) {
if (await existsOrFault(fs, join(cur, ".git"), { kind: "marker_unreadable", reason: "repo_root_unreadable" }))
return cur;
const parent = dirname(cur);
if (parent === cur)
return undefined;
cur = parent;
}
}
export async function resolveProjectId(fs, rootDir) {
const dir = resolve(rootDir);
const gitRoot = await gitRootOf(fs, dir);
const projectRoot = gitRoot ?? dir;
if (gitRoot !== undefined) {
let cur = dir;
while (cur !== gitRoot) {
const nestedPath = join(cur, PROJECT_MARKER_PATH);
if (await existsOrFault(fs, nestedPath, markerUnreadable(dir, cur, "io_error"))) {
throw identityError("config.memory_project_marker_nested", `nested project marker: ${nestedPath} sits below the repo root (${gitRoot}) — ` +
`this version supports ONE marker, at the repo root; remove the nested marker or split the repo.`, markerUnreadable(dir, cur, "nested"));
}
const parent = dirname(cur);
if (parent === cur)
break;
cur = parent;
}
}
const markerFile = join(projectRoot, PROJECT_MARKER_PATH);
if (!(await existsOrFault(fs, markerFile, markerUnreadable(dir, projectRoot, "io_error"))))
return null;
const body = await readOrFault(markerFile, () => fs.readTextFile(markerFile), markerUnreadable(dir, projectRoot, "io_error"));
let parsed;
try {
parsed = parseProjectMarker(body);
}
catch (e) {
if (isMarkerFault(e)) {
const reason = CORRUPT_MARKER_REASON.get(e) ?? "unparseable";
throw identityError("config.memory_project_marker", e.message, markerUnreadable(dir, projectRoot, reason));
}
throw e;
}
if (!parsed)
return null;
return { projectId: parsed.projectId, markerDir: projectRoot };
}
export function projectMarkerUnreadableOf(fault) {
const d = fault?.detail;
if (d === undefined || d.kind !== "marker_unreadable")
return undefined;
return d.reason === "repo_root_unreadable" || d.markerPath === undefined ? { reason: d.reason } : { reason: d.reason, markerPath: d.markerPath };
}
export async function resolveSessionProject(fs, taskRoot, declared, inherited) {
const declaredId = declared !== undefined ? normalizeProjectId(declared.id) : undefined;
let marker;
try {
marker = await resolveProjectId(fs, taskRoot);
}
catch (e) {
if (!isMarkerFault(e) || declaredId !== undefined)
throw e;
return { root: taskRoot, markerFault: e };
}
if (marker !== null && declaredId !== undefined && declaredId !== marker.projectId) {
const markerPath = join(marker.markerDir, PROJECT_MARKER_PATH);
throw identityError("config.project_identity_mismatch", `TaskSpec.project.id declares ${declaredId}, but this checkout's project marker ${markerPath} carries ${marker.projectId} — ` +
`the leg is refused rather than filed under the wrong project. Declare the marker's id, or correct the marker.`, { kind: "mismatch", declared: declaredId, marker: marker.projectId, markerPath });
}
const verdict = marker !== null ? { id: marker.projectId, source: "marker" }
: declaredId !== undefined ? { id: declaredId, source: "declared" }
: inherited !== undefined ? { id: normalizeProjectId(inherited.id), source: "declared" }
: undefined;
if (verdict === undefined)
return { root: taskRoot };
const owner = declared ?? (inherited !== undefined && normalizeProjectId(inherited.id) === verdict.id ? inherited : undefined);
return { root: taskRoot, project: verdict, seat: Object.freeze({ ...owner, id: verdict.id }) };
}
export function assertMemoryProjectVerdict(sessionProject, scopes, writeScope) {
const consumesProjectIdentity = [...scopes, ...(writeScope !== null ? [writeScope] : [])]
.map(parseScopeKey)
.some((k) => k.kind === "proj" || k.kind === "userproj");
if (sessionProject.markerFault !== undefined && consumesProjectIdentity)
throw sessionProject.markerFault;
if (writeScope === null)
return;
const w = parseScopeKey(writeScope);
if (w.kind !== "proj" && w.kind !== "userproj")
return;
const verdict = sessionProject.project;
if (verdict === undefined) {
throw identityError("config.memory_project_identity", `memory scope contract v2: writeScope ${writeScope} targets projectId ${w.projectId}, ` +
`but this leg has no project verdict (no .sema/project marker and no TaskSpec.project) — refusing a project-scoped write without a project identity.`, { kind: "write_without_verdict", writeScope, writeProjectId: w.projectId });
}
if (normalizeProjectId(w.projectId) !== normalizeProjectId(verdict.id)) {
throw identityError("config.memory_project_identity", `memory scope contract v2: writeScope ${writeScope} targets projectId ${w.projectId}, ` +
`but this leg's project verdict (${verdict.source === "marker" ? "marker .sema/project" : "declared TaskSpec.project.id"}) is ${verdict.id} — refusing a mis-addressed write.`, { kind: "write_project_mismatch", writeScope, writeProjectId: w.projectId, verdictProjectId: verdict.id, verdictSource: verdict.source });
}
}