UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

678 lines (677 loc) • 35.5 kB
import { randomBytes } from "node:crypto"; import { existsSync } from "node:fs"; import { readdirSync, readFileSync } from "../descriptor-seat.js"; import { join, resolve } from "node:path"; import { adoptRuleBucket } from "../permission-rule-adopt.js"; import { BootLock, atomicWriteFile, ensureDir, scopeLabelOf } from "../fs-atomic.js"; import { rekeySessionPolicyDirectory } from "../session-policy-store.js"; import { refileToolResultDirectory, rekeyToolResultDirectory } from "../tool-result-store.js"; import { CHECKPOINT_LEDGER, rekeyCheckpointDirectory } from "../checkpoint-store.js"; import { BACKGROUND_AGENT_LEDGER, lookBackgroundAgentDirectory, rekeyBackgroundAgentDirectory } from "../background-agent-store.js"; import { normalizeToolResultProvenance } from "../../../core/tool-result-store.js"; import { recordedOwnerIdentityOf } from "../../../core/owner-identity.js"; import { readIdentityRekeyInput } from "../../../core/identity-rekey.js"; import { thrownText } from "../../../core/thrown-value.js"; import { AdoptionError, NOT_MIGRATED_BY_DESIGN, readRootAdoptionFile, writeRootAdoptionFile, } from "./marker.js"; import { readRecordedRuleOwner, ruleOwnerText, sameRuleOwner } from "../../../core/rule-owner.js"; import { holdsUnpairedSurrogate, judgePrincipalName, unpairedSurrogateRefusal } from "../../../core/principal-name.js"; const CONFIG_ACCOUNT_FILE = "adoption-configs.json"; function baselineConfigs(toPrincipal) { return [ { deployment: "web-client-bff", key: "injected-principal", requiredValue: toPrincipal, migrated: false }, { deployment: "cli", key: "cloud-credentials+profiles", requiredValue: toPrincipal, migrated: false }, { deployment: "cli", key: "SEMA_LIVE_PRINCIPAL", requiredValue: toPrincipal, migrated: false }, { deployment: "env", key: "REQUIRE_PRINCIPAL", requiredValue: "true", migrated: false }, { deployment: "core-decl", key: "localOwnerRules", requiredValue: "withdrawn", migrated: false }, ]; } function readConfigAccount(root) { let raw; try { raw = readFileSync(join(root, CONFIG_ACCOUNT_FILE), "utf8"); } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } let parsed; try { parsed = JSON.parse(raw); } catch (err) { throw new AdoptionError("adoption_marker_corrupt", `the adoption config account in ${root} is not valid JSON (${err.message})`); } if (!isConfigAccountShape(parsed)) { throw new AdoptionError("adoption_marker_corrupt", `the adoption config account in ${root} does not carry a readable shape`); } return parsed; } function readConfigAccountEvidence(root) { try { return readConfigAccount(root); } catch (err) { if (err instanceof AdoptionError) return undefined; throw err; } } function isConfigAccountShape(v) { if (v === null || typeof v !== "object") return false; const f = v; if (f.schemaVersion !== 1 || typeof f.adoptionId !== "string" || !Array.isArray(f.configs)) return false; const finite = (n) => typeof n === "number" && Number.isFinite(n); return f.configs.every((c) => { if (c === null || typeof c !== "object") return false; const e = c; if (typeof e.deployment !== "string" || typeof e.key !== "string" || typeof e.requiredValue !== "string" || typeof e.migrated !== "boolean") { return false; } if (e.ack !== undefined) { if (e.ack === null || typeof e.ack !== "object" || !finite(e.ack.atMs)) return false; } if (e.witnessed !== undefined) { if (e.witnessed === null || typeof e.witnessed !== "object") return false; const w = e.witnessed; if (!finite(w.atMs) || w.receipt === null || typeof w.receipt !== "object") return false; const r = w.receipt; if (r.adoptionId !== f.adoptionId || r.deployment !== e.deployment || r.key !== e.key || r.observedValue !== e.requiredValue || !finite(r.atMs)) { return false; } } return true; }); } function writeConfigAccount(root, account) { atomicWriteFile(join(root, "tmp"), join(root, CONFIG_ACCOUNT_FILE), JSON.stringify(account, null, 2)); } function configIdentity(c) { return JSON.stringify([c.deployment, c.key]); } function upsertConfigAccount(root, adoptionId, toPrincipal, additional) { const existing = readConfigAccount(root); if (existing !== undefined && existing.adoptionId === adoptionId) { const known = new Set(existing.configs.map(configIdentity)); let grew = false; for (const c of additional) { if (!known.has(configIdentity(c))) { existing.configs.push({ ...c }); known.add(configIdentity(c)); grew = true; } } if (grew) writeConfigAccount(root, existing); return; } const merged = new Map(); for (const c of baselineConfigs(toPrincipal)) merged.set(configIdentity(c), c); for (const c of additional) merged.set(configIdentity(c), c); writeConfigAccount(root, { schemaVersion: 1, adoptionId, configs: [...merged.values()] }); } function outstandingOf(account) { if (account === undefined) return []; return account.configs.filter((c) => c.witnessed === undefined).map((c) => `${c.deployment}:${c.key}`); } export function ackAdoptionConfig(root, deployment, key, now) { const account = readConfigAccount(root); const entry = account?.configs.find((c) => c.deployment === deployment && c.key === key); if (account === undefined || entry === undefined) { throw new AdoptionError("adoption_witness_mismatch", `no adoption config account entry for ${deployment}:${key} in ${root}`); } entry.ack = { atMs: (now ?? Date.now)() }; writeConfigAccount(root, account); } export function witnessAdoptionConfig(root, receipt) { const account = readConfigAccount(root); const entry = account?.configs.find((c) => c.deployment === receipt.deployment && c.key === receipt.key); if (account === undefined || entry === undefined) { throw new AdoptionError("adoption_witness_mismatch", `no adoption config account entry for ${receipt.deployment}:${receipt.key} in ${root}`); } if (receipt.adoptionId !== account.adoptionId) { throw new AdoptionError("adoption_witness_mismatch", `the witness receipt names adoption "${receipt.adoptionId}" but this root's adoption is "${account.adoptionId}" — a witness binds to the adoption it observed`); } if (typeof receipt.atMs !== "number" || !Number.isFinite(receipt.atMs)) { throw new AdoptionError("adoption_witness_mismatch", `the witness receipt carries an invalid timestamp (${String(receipt.atMs)}) — refusing to record evidence the account reader would reject`); } if (receipt.observedValue !== entry.requiredValue) { throw new AdoptionError("adoption_witness_mismatch", `the witness for ${receipt.deployment}:${receipt.key} observed "${receipt.observedValue}" but the adoption requires "${entry.requiredValue}" — refusing to clear the account on a value that would leave the consumer locked out`); } entry.witnessed = { atMs: receipt.atMs, receipt }; writeConfigAccount(root, account); } const QUARANTINE_DIR = "adoption-quarantine"; export function listAdoptionQuarantine(root) { const base = join(root, QUARANTINE_DIR); let stores; try { stores = readdirSync(base); } catch (err) { if (err.code === "ENOENT") return []; throw err; } const out = []; for (const store of stores) { let names; try { names = readdirSync(join(base, store)); } catch { continue; } for (const name of names) out.push({ store, name, path: join(base, store, name) }); } return out; } function quarantineRow(root, store, name, bytes) { const dir = join(root, QUARANTINE_DIR, scopeLabelOf(store)); ensureDir(dir); const base = scopeLabelOf(name); let target = join(dir, base); for (let i = 2; existsSync(target); i += 1) { if (readFileSync(target, "utf8") === bytes) return; target = join(dir, `${base}.${i}`); } atomicWriteFile(join(root, "tmp"), target, bytes); } async function planOrRefuse(store, step) { const names = []; const answer = (await step("plan", (name) => names.push(name))); if (answer.conflicting === 0) return answer; throw new AdoptionError("adoption_row_collision", `${answer.conflicting} ${store} row(s) carry an identity this adoption changes but cannot be read as one by this engine (${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""}) — ` + `repair or remove them (a row a newer engine wrote: run the adoption with that engine), then run the adoption again; this leg moved nothing`); } const oneStepLeg = (store, step, ledger) => ({ store, first: "plan", step, look: () => planOrRefuse(store, step), ...(ledger !== undefined ? { ledger } : {}) }); function identitySeatLegsOf(root, from, toPrincipal, plan) { const sessionPolicy = join(root, "session-policy"); const toolResults = join(root, "tool-results"); const policyLeg = { store: SESSION_POLICY_LEG, first: "arrive", step: (mode) => rekeySessionPolicyDirectory(sessionPolicy, { from, toPrincipal, mode }, undefined) }; if (from.kind === "local-owner") { const judge = (record) => { const recorded = recordedOwnerIdentityOf(record); if (recorded === "none" || recorded === "unreadable" || recorded.principal !== null) return { kind: "untouched" }; const identity = { principal: toPrincipal, ...(recorded.isolationScope !== undefined ? { isolationScope: recorded.isolationScope } : {}) }; return { kind: "rekeyed", owner: normalizeToolResultProvenance({ sessionId: record.sessionId, taskId: record.taskId, ...identity }), partitionLeft: false }; }; return [policyLeg, oneStepLeg(TOOL_RESULT_LEG, (mode, onUnrekeyable) => refileToolResultDirectory(toolResults, mode, judge, onUnrekeyable))]; } const scopes = scopeMappingOf(from, toPrincipal, plan); const map = { fromPrincipal: from.principal, toPrincipal, scopes }; const moving = scopes.filter((p) => p.fromScope !== p.toScope); const agentStep = async (mode) => { if (mode === "arrive") { let [rows, conflicting] = [0, 0]; for (const pair of moving) { const plan = await rekeyBackgroundAgentDirectory(root, { ...pair, mode: "plan" }); if (plan.kind === "plan" || plan.kind === "conflict") [rows, conflicting] = [rows + plan.rows, conflicting + plan.conflicting]; } if (conflicting > 0) return { kind: "conflict", mode: "arrive", rows, conflicting }; } let rows = 0; for (const pair of moving) { const answer = await rekeyBackgroundAgentDirectory(root, { ...pair, mode }); if (answer.kind === "conflict") return answer; rows += answer.rows; } return { kind: "done", mode, rows }; }; return [ policyLeg, oneStepLeg(CHECKPOINT_LEG, (mode, onUnrekeyable) => rekeyCheckpointDirectory(root, { ...map, mode }, onUnrekeyable), CHECKPOINT_LEDGER.name), oneStepLeg(TOOL_RESULT_LEG, (mode, onUnrekeyable) => rekeyToolResultDirectory(toolResults, { ...map, mode }, onUnrekeyable)), { store: BACKGROUND_AGENT_LEG, ledger: BACKGROUND_AGENT_LEDGER.name, first: "arrive", step: agentStep, look: () => lookBackgroundAgentDirectory(root) }, ]; } function scopeMappingOf(from, toPrincipal, plan) { return plan.scopes ?? [{ fromScope: from.principal, toScope: toPrincipal }]; } function readAdoptionScopes(from, toPrincipal, raw) { if (raw === undefined) return undefined; if (from.kind !== "principal") { throw new AdoptionError("adoption_bad_request", "`scopes` maps a person's partitions and applies to a principal → principal adoption; a local-owner adoption re-files the anonymous identity's entries and keeps each one's partition"); } let scopes; try { scopes = readIdentityRekeyInput("adoptLocalDataRoot", { fromPrincipal: from.principal, toPrincipal, scopes: raw, mode: "plan" }).scopes; } catch (e) { throw new AdoptionError("adoption_bad_request", e.message); } const own = scopes.length === 1 && scopes[0].fromScope === from.principal && scopes[0].toScope === toPrincipal; return own ? undefined : scopes.map((p) => ({ fromScope: p.fromScope, toScope: p.toScope })); } function sameScopeMapping(a, b) { const key = (m) => (m === undefined ? "own" : JSON.stringify(m.map((p) => JSON.stringify([p.fromScope, p.toScope])).sort())); return key(a) === key(b); } export function adoptionLegStillReads(root, ledger) { const file = readRootAdoptionFile(root); if (file === undefined || !("marker" in file)) return false; const bits = file.marker.legs ?? {}; return identitySeatLegsOf(root, file.marker.from, file.marker.toPrincipal, file.marker.plan).some((leg) => leg.ledger === ledger && bits[leg.store]?.done !== true); } async function runSeatLeg(leg, toPrincipal, between, onBetween) { let rows = between?.rows ?? 0; if (between === undefined) { const answer = leg.first === "plan" ? await planOrRefuse(leg.store, leg.step) : await leg.step("arrive"); if (answer.kind === "conflict") { throw new AdoptionError("adoption_row_collision", `${answer.conflicting} ${leg.store} key(s) already hold a row under "${toPrincipal}" that is not this adoption's arrival (or carry a lineage nobody can vouch for) — ` + `merging two existing rows is a sync join, not a re-key; nothing was moved and the adoption marker is left in place for inspection`); } rows = answer.rows; onBetween(rows); } await leg.step("leave"); return rows; } const ZERO_ACTION_STORES = [ "session", "file-snapshot", "memory", "memory-engine", "task-list", "mailbox", "workflow-run", "workflow-journal", ]; const SESSION_POLICY_LEG = "session-policy"; const CHECKPOINT_LEG = "checkpoint"; const TOOL_RESULT_LEG = "tool-result"; const BACKGROUND_AGENT_LEG = "background-agent"; const SEAT_LEGS = [SESSION_POLICY_LEG, CHECKPOINT_LEG, TOOL_RESULT_LEG, BACKGROUND_AGENT_LEG]; const betweenBitOf = (leg) => `${leg.store}:${leg.first === "plan" ? "planned" : "arrived"}`; const CARRIAGE_BIT_PREFIX = "carriage:"; function receiptFromTerminal(root, adopted) { const account = readConfigAccountEvidence(root); const accountBinds = account !== undefined && account.adoptionId === adopted.immutableReport.adoptionId; return { status: "adopted", immutableReport: adopted.immutableReport, current: { outstandingConfigs: accountBinds ? outstandingOf(account) : adopted.immutableReport.affectedDeploymentConfigs.map((c) => `${c.deployment}:${c.key}`), quarantined: listAdoptionQuarantine(root).length, }, }; } function rebuildConfigAccountIfUnbound(root, report) { const account = readConfigAccountEvidence(root); if (account !== undefined && account.adoptionId === report.adoptionId) return; writeConfigAccount(root, { schemaVersion: 1, adoptionId: report.adoptionId, configs: report.affectedDeploymentConfigs.map((c) => ({ ...c })), }); } export function readAdoptionStatus(root) { const f = readRootAdoptionFile(root); if (f === undefined) return { state: "none" }; if ("marker" in f) { return { state: "in-flight", from: f.marker.from, toPrincipal: f.marker.toPrincipal, phase: f.marker.phase }; } return { state: "adopted", receipt: receiptFromTerminal(root, f.adopted) }; } function refuseUnnameableRuleSource(from, rulesDir) { if (from.kind === "principal" && holdsUnpairedSurrogate(from.principal)) throw new AdoptionError("adoption_bad_request", unpairedSurrogateRefusal("adoptLocalDataRoot: the source principal (from.principal) of a rules leg")); return rulesDir; } function answerFromExisting(root, existing, from, toPrincipal, scopes) { if (existing === undefined) return undefined; if ("adopted" in existing) { const sameMove = existing.adopted.toPrincipal === toPrincipal && sameRuleOwner(existing.adopted.from, from); if (sameMove && sameScopeMapping(existing.adopted.immutableReport.scopes, scopes)) { return receiptFromTerminal(root, existing.adopted); } throw new AdoptionError("adoption_retarget", `this data root already carries a completed adoption (${ruleOwnerText(existing.adopted.from)} → "${existing.adopted.toPrincipal}") — ` + (sameMove ? `under another partition mapping; its rows are where that mapping put them, and a re-run answers its receipt only with the same mapping` : `a second adoption of the same root is a multi-tenant transfer, not a shape this protocol supports`)); } if (existing.marker.toPrincipal !== toPrincipal || !sameRuleOwner(existing.marker.from, from)) { throw new AdoptionError("adoption_in_flight_mismatch", `an adoption toward "${existing.marker.toPrincipal}" is already in flight in this data root (phase ${existing.marker.phase}) — ` + `refusing to start a different one (resume the original, or repair the marker by hand)`); } return undefined; } export async function adoptLocalDataRoot(opts) { const target = judgePrincipalName(opts.toPrincipal); if (!target.ok) { throw new AdoptionError("adoption_bad_request", `adoptLocalDataRoot requires the adopting principal, a principal name — adoption is the act of giving this data root an identity — got ${target.fault}`); } const from = readRecordedRuleOwner(opts.from); if (from === undefined) { throw new AdoptionError("adoption_bad_request", "the adoption source must be the local-owner kind or a principal owner whose principal is a principal name — local-single-user identity is the local-owner kind, never a blank string"); } if (from.kind === "principal" && from.principal === opts.toPrincipal) { throw new AdoptionError("adoption_bad_request", `the data root already belongs to "${opts.toPrincipal}" — there is nothing to adopt`); } const requestedScopes = readAdoptionScopes(from, opts.toPrincipal, opts.scopes); if (typeof opts.credentials.ref !== "string" || opts.credentials.ref === "") { throw new AdoptionError("adoption_bad_request", "the credentials claim ref must be a non-empty reference (the claim is what makes the new identity redeemable)"); } if (opts.credentials === null || typeof opts.credentials !== "object") { throw new AdoptionError("adoption_bad_request", "adoptLocalDataRoot requires a `credentials` object"); } if (opts.additionalConfigs !== undefined && !Array.isArray(opts.additionalConfigs)) { throw new AdoptionError("adoption_bad_request", "additionalConfigs must be an array when supplied"); } if (opts.carriage !== undefined && !Array.isArray(opts.carriage)) { throw new AdoptionError("adoption_bad_request", "carriage must be an array when supplied"); } if (opts.rules !== undefined && (opts.rules === null || typeof opts.rules !== "object")) { throw new AdoptionError("adoption_bad_request", "rules must be an object when supplied"); } if (opts.now !== undefined && typeof opts.now !== "function") { throw new AdoptionError("adoption_bad_request", "`now` must be callable when supplied — it publishes the terminal timestamp"); } if (opts.onError !== undefined && typeof opts.onError !== "function") { throw new AdoptionError("adoption_bad_request", "`onError` must be callable when supplied"); } if (opts.credentials.issuedBy !== "server") { throw new AdoptionError("adoption_bad_request", `the credentials claim must be server-issued (got issuedBy: ${JSON.stringify(opts.credentials.issuedBy)}) — the server mints the new identity`); } for (const c of opts.additionalConfigs ?? []) { if (c === null || typeof c !== "object" || typeof c.deployment !== "string" || c.deployment === "" || typeof c.key !== "string" || c.key === "" || typeof c.requiredValue !== "string" || typeof c.migrated !== "boolean") { throw new AdoptionError("adoption_bad_request", `a malformed additionalConfigs entry (${JSON.stringify(c)}) — each entry is { deployment, key, requiredValue: strings; migrated: boolean }`); } } if (opts.rules !== undefined && (typeof opts.rules.dir !== "string" || opts.rules.dir === "" || typeof opts.rules.transport !== "function")) { throw new AdoptionError("adoption_bad_request", "a rules leg needs a non-empty bucket directory and a transport function"); } { const seen = new Set(); for (const leg of opts.carriage ?? []) { if (leg === null || typeof leg !== "object" || typeof leg.store !== "string" || leg.store === "" || typeof leg.run !== "function") { throw new AdoptionError("adoption_bad_request", "a carriage leg is { store: non-empty string; run: function }"); } if (seen.has(leg.store)) { throw new AdoptionError("adoption_bad_request", `two carriage legs share the store name "${leg.store}" — a leg's plan identity is its store family, one leg per store`); } seen.add(leg.store); } } ensureDir(opts.root); const pre = answerFromExisting(opts.root, readRootAdoptionFile(opts.root), from, opts.toPrincipal, requestedScopes); if (pre !== undefined) { const account = readConfigAccountEvidence(opts.root); if (account !== undefined && account.adoptionId === pre.immutableReport.adoptionId) return pre; } const engineLock = BootLock.fence(opts.root, "LOCK"); try { engineLock.acquire(); } catch (err) { throw new AdoptionError("adoption_locked", `a live instance owns this data root — stop the engine before adopting: ${err.message}`); } const adoptionLock = BootLock.fence(opts.root, "ADOPTION-LOCK"); try { adoptionLock.acquire(); } catch (err) { engineLock.release(); throw new AdoptionError("adoption_locked", `another adoption owns this data root: ${err.message}`); } try { const existing = readRootAdoptionFile(opts.root); const answered = answerFromExisting(opts.root, existing, from, opts.toPrincipal, requestedScopes); if (answered !== undefined) { rebuildConfigAccountIfUnbound(opts.root, answered.immutableReport); return receiptFromTerminal(opts.root, { from: answered.immutableReport.from, toPrincipal: answered.immutableReport.toPrincipal, atMs: answered.immutableReport.atMs, immutableReport: answered.immutableReport, }); } const now = opts.now ?? Date.now; const offeredScopes = requestedScopes; const offeredRulesDir = opts.rules !== undefined ? resolve(opts.rules.dir) : undefined; const offeredCarriage = (opts.carriage ?? []).map((l) => l.store); let phase; let adoptionId; let legBits; let plan; if (existing !== undefined && "marker" in existing) { phase = existing.marker.phase; adoptionId = existing.marker.adoptionId; legBits = existing.marker.legs ?? {}; plan = existing.marker.plan; const missing = []; if (plan.rulesDir !== undefined && offeredRulesDir !== plan.rulesDir) { missing.push(`the permission-rule leg over "${plan.rulesDir}"${offeredRulesDir !== undefined ? ` (offered "${offeredRulesDir}")` : ""}`); } const offered = new Set(offeredCarriage); for (const store of plan.carriage) if (!offered.has(store)) missing.push(`the "${store}" carriage leg`); if (plan.credentialsRef !== opts.credentials.ref) missing.push(`the credentials claim (recorded "${plan.credentialsRef}")`); if (!sameScopeMapping(plan.scopes, offeredScopes)) missing.push(`the partition mapping recorded at the start (${plan.scopes === undefined ? "the person's own pair alone" : `${plan.scopes.length} pair(s)`}; offered ${offeredScopes === undefined ? "the person's own pair alone" : `${offeredScopes.length} pair(s)`})`); if (missing.length > 0) { throw new AdoptionError("adoption_plan_mismatch", `this resume supplies less than the adoption's recorded plan — missing: ${missing.join("; ")}. ` + `Re-run with the original legs (growing the plan is fine, shrinking it is not), or repair the marker by hand.`); } const lateAdds = []; if (plan.rulesDir === undefined && offeredRulesDir !== undefined) { if (phase < 3) plan = { ...plan, rulesDir: refuseUnnameableRuleSource(from, offeredRulesDir) }; else lateAdds.push(`the permission-rule leg (stage ③ already completed at phase ${phase})`); } const knownCarriage = new Set(plan.carriage); const newCarriage = offeredCarriage.filter((s) => !knownCarriage.has(s)); if (newCarriage.length > 0) { if (phase < 5) plan = { ...plan, carriage: [...plan.carriage, ...newCarriage] }; else lateAdds.push(`the ${newCarriage.map((s) => `"${s}"`).join("/")} carriage leg(s) (stage ⑤ already completed)`); } if (lateAdds.length > 0) { throw new AdoptionError("adoption_plan_mismatch", `this resume offers legs whose stage has already completed — ${lateAdds.join("; ")}. ` + `They would never run, and reporting them as done would be a lie; post-adoption carriage rides each store's normal channel.`); } if (plan !== existing.marker.plan) { publishMarker(opts.root, adoptionId, from, opts.toPrincipal, phase, plan, legBits); } const accountInFlight = readConfigAccount(opts.root); if (accountInFlight === undefined || accountInFlight.adoptionId !== adoptionId) { throw new AdoptionError("adoption_marker_corrupt", `the adoption config account is ${accountInFlight === undefined ? "missing" : "bound to a different adoption"} while an adoption is in flight — ` + `it lands before the marker and never disappears mid-arc; restore it before resuming`); } upsertConfigAccount(opts.root, adoptionId, opts.toPrincipal, opts.additionalConfigs ?? []); } else { plan = { ...(offeredRulesDir !== undefined ? { rulesDir: refuseUnnameableRuleSource(from, offeredRulesDir) } : {}), carriage: offeredCarriage, credentialsRef: opts.credentials.ref, ...(offeredScopes !== undefined ? { scopes: offeredScopes } : {}) }; for (const leg of identitySeatLegsOf(opts.root, from, opts.toPrincipal, plan)) await leg.look?.(); adoptionId = `adp_${randomBytes(8).toString("hex")}`; phase = 2; legBits = {}; upsertConfigAccount(opts.root, adoptionId, opts.toPrincipal, opts.additionalConfigs ?? []); publishMarker(opts.root, adoptionId, from, opts.toPrincipal, 2, plan, legBits); } const legs = []; if (phase < 3) { if (opts.rules !== undefined) { let nested; try { nested = await adoptRuleBucket({ dir: opts.rules.dir, from, toPrincipal: opts.toPrincipal, transport: opts.rules.transport, ...(opts.now !== undefined ? { now: opts.now } : {}), ...(opts.onError !== undefined ? { onError: opts.onError } : {}), }, "plan"); } catch (err) { if (err instanceof AdoptionError) throw err; throw new AdoptionError("adoption_rule_leg_refused", `the permission-rule leg refused: ${thrownText(err)}`); } if (nested.status === "stalled") { return { status: "stalled", phase: 2, error: `the permission-rule leg stalled (its own marker holds phase ${nested.phase}): ${nested.error}`, }; } } } for (const leg of identitySeatLegsOf(opts.root, from, opts.toPrincipal, plan)) { if (legBits[leg.store]?.done === true) continue; const at = phase; const rows = await runSeatLeg(leg, opts.toPrincipal, legBits[betweenBitOf(leg)], (firstRows) => { legBits = { ...legBits, [betweenBitOf(leg)]: { done: true, rows: firstRows } }; publishMarker(opts.root, adoptionId, from, opts.toPrincipal, at, plan, legBits); }); legBits = { ...legBits, [leg.store]: { done: true, rows } }; publishMarker(opts.root, adoptionId, from, opts.toPrincipal, at, plan, legBits); } if (phase < 3) { publishMarker(opts.root, adoptionId, from, opts.toPrincipal, 3, plan, legBits); phase = 3; } if (phase < 4) { publishMarker(opts.root, adoptionId, from, opts.toPrincipal, 4, plan, legBits); phase = 4; } if (phase < 5) { for (const leg of opts.carriage ?? []) { if (legBits[`${CARRIAGE_BIT_PREFIX}${leg.store}`]?.done === true) continue; let quarantined = 0; const ctx = { quarantine: (name, bytes) => { quarantineRow(opts.root, leg.store, name, bytes); quarantined += 1; }, }; let rows; try { const res = await leg.run(ctx); rows = res === undefined ? undefined : res.rows; } catch (err) { return { status: "stalled", phase: 4, error: `the "${leg.store}" carriage leg failed: ${thrownText(err)} — resume when it is healthy`, }; } if (rows !== undefined && (!Number.isSafeInteger(rows) || rows < 0)) { return { status: "stalled", phase: 4, error: `the "${leg.store}" carriage leg reported an invalid row count (${String(rows)}) — a leg reports a non-negative integer or nothing; fix the leg and resume`, }; } legBits = { ...legBits, [`${CARRIAGE_BIT_PREFIX}${leg.store}`]: { done: true, ...(rows !== undefined ? { rows } : {}), ...(quarantined > 0 ? { quarantined } : {}), }, }; publishMarker(opts.root, adoptionId, from, opts.toPrincipal, 4, plan, legBits); } publishMarker(opts.root, adoptionId, from, opts.toPrincipal, 5, plan, legBits); phase = 5; } if (plan.rulesDir !== undefined) legs.push({ store: "permission-rule", action: "bucket-rebind" }); const unmoved = []; for (const store of SEAT_LEGS) { const bit = legBits[store]; if (bit?.done === true) legs.push({ store, action: "row-rewrite", rows: bit.rows ?? 0 }); else unmoved.push(store); } const carried = Object.entries(legBits) .filter(([k]) => k.startsWith(CARRIAGE_BIT_PREFIX)) .map(([k, bit]) => ({ store: k.slice(CARRIAGE_BIT_PREFIX.length), action: "carried", ...(bit.rows !== undefined ? { rows: bit.rows } : {}), ...(bit.quarantined !== undefined ? { quarantined: bit.quarantined } : {}), })); legs.push(...carried); const carriedNames = new Set(carried.map((l) => l.store)); for (const store of [...ZERO_ACTION_STORES, ...unmoved]) { if (!carriedNames.has(store)) legs.push({ store, action: "none" }); } legs.push({ store: "usage-window", action: "reset" }); const account = readConfigAccount(opts.root); const atMs = now(); if (!Number.isSafeInteger(atMs) || atMs < 0) { return { status: "stalled", phase: 5, error: `the clock returned an invalid timestamp (${String(atMs)}) — refusing to publish a terminal record the reader would reject; fix the injected clock and resume`, }; } const immutableReport = { adoptionId, from, toPrincipal: opts.toPrincipal, atMs, credentials: opts.credentials, affectedDeploymentConfigs: (account?.configs ?? []).map(({ deployment, key, requiredValue, migrated }) => ({ deployment, key, requiredValue, migrated })), legs, notMigratedByDesign: NOT_MIGRATED_BY_DESIGN.map((e) => ({ ...e })), ...(plan.scopes !== undefined ? { scopes: plan.scopes.map((p) => ({ ...p })) } : {}), }; writeRootAdoptionFile(opts.root, { schemaVersion: 1, adopted: { from, toPrincipal: opts.toPrincipal, atMs: immutableReport.atMs, immutableReport }, }); return receiptFromTerminal(opts.root, { from, toPrincipal: opts.toPrincipal, atMs: immutableReport.atMs, immutableReport }); } finally { adoptionLock.release(); engineLock.release(); } } function publishMarker(root, adoptionId, from, toPrincipal, phase, plan, legs) { const marker = { adoptionId, from, toPrincipal, phase, ...(Object.keys(legs).length > 0 ? { legs } : {}) }; writeRootAdoptionFile(root, plan.scopes !== undefined ? { schemaVersion: 2, marker: { ...marker, plan: { ...plan, scopes: plan.scopes } } } : { schemaVersion: 1, marker: { ...marker, plan } }); }