mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
* fix(desktop): release a capture when its start is cancelled after launch Cancelling start_build_capture during the opened app's screenshot left the capture running, so the next start was refused. The capture is now kept for the owner's cleanup, and the next start stops it first. * fix(desktop): keep a published witness error and tag an app data refusal A second failure to close a published witness returns the original error, so its record and cleanup lease stay bound. A reset the app itself refuses is an AppDataRefusal; only a reply that is not that refusal stays unsettled. A missing child of a cut view is undecided with the same description in both evaluators, and the shared cases cover it. * fix(desktop): align a cut view's missing text with the Python check A missing child of a truncated view is undecided for the same sentence in both evaluators, including the pointer the view does not contain. * fix(desktop): keep one published witness cleanup across retries A published record and its bound cleanup error stay together. A later close failure returns that error, and the unused path that built a fresh adapter error is gone. * fix(desktop): keep a bundle task read inside the witness result A cancelled, refused, or failed read of the bundle's task files returns the witness's Result, including a cleanup lease when a handle would not close. * test(desktop): pass the settle timing when reading a witness bundle The witness takes the settle timing before the bundle path, so the bundle-read tests keep the path in its own argument. * fix(desktop): bound a guest file answer and split a long controller argument A data/get whose base64 answer would exceed a quarter of the V8 heap is refused before it is read. Controller JSON that exceeds Linux's single-argument limit travels as several arguments the controller joins. * fix(desktop): keep an underreported guest file from raising its read A data/get answer is admitted only when its base64 body fits in the heap quarter after the copies held during parse. Decoded bytes larger than the computer reported are dropped. * fix(desktop): grade shipped seeds and keep selected settings and sqlite logs Seed checks follow the files the bundle ships, so an omitted lock is absent. An incomplete checkpoint is not reported as no change. A selected link keeps its spelling, and a database's wal and journal stay supporting state. Closing the fake computer stops a detached capture. * fix(desktop): keep added-record checks off ids, dates, and joined timestamps A position-named record's fields keep their paths, so an identifier, a stamped date, and text past the limit are not suggested checks. A whole-text check does not climb into an ancestor whose text joins a timestamp. * fix(desktop): bound home fetches and keep unsettled edits readable Split home-folder reads by the guest answer budget, keep a capacity error from the capture output, and drop the superseded task-argument refusal. Grade kept text per line, leave unretained dconf unread, and reserve by-position notes for XML children. Map a linked database's sidecars through the selected spelling and stop a detached capture only when its start identity still owns the pid. * fix(desktop): describe unretained dconf as unread The key comparison treats a missing copy as unknown. The comment still said that copy counted as an empty key list. * test(desktop): keep a capture capacity error through endedCapture An output past the guest answer ceiling stays the resource constraint, with its heap recovery and non-retryable status, instead of a generic capture-exit message. * fix(desktop): keep nested save times and formatting runs out of checks A field check drops save-time leaves before it joins the field, so a nested timestamp is not part of the suggested text. A text check beside a save time uses the paragraph when the diff names a formatting run. * test(desktop): read paragraph pointers from checks that have them * test(desktop): expect a large task to export intact The 96 KiB refusal is gone. A prompt past that size reaches the computer and comes back unchanged, instead of failing before export. * fix(desktop): keep real edits that save-side heuristics were dropping Repeated unnamed fields stay content checks. A formula that still has text is not renumbered with its ExprID. One gained style attribute is the edit; a repeated fill-in stays upkeep. Phone numbers and plain clock times stay text, and a decimal is the element's whole text. An older verifier matches on the task it states, not its evaluator source. * fix(desktop): cover repeated records and keep timestamps out of checks An added record whose words are already in the seed still gets the list's text when that text fits. Readiness is a start reason, so a final check names seed locks without matching the message. Field text split by a timestamp stays separate, and a timestamp line is not offered as a guard. * fix(desktop): compare a cell's joined decimal within tolerance The whole-element check keeps numeric tolerance, so 437.80 and a long float still match 437.8, including when a run splits the digits. A different number or other text does not. Both evaluators read an element's text for that comparison. * fix(desktop): grade a number from a complete XML element only A tolerance check joins an element's text only in an XML file or an XML archive entry, and leaves that check undecided when the view is cut, so a dropped descendant cannot turn the kept runs into a passing number. A JSON object with the same shape stays the value itself. Equivalent decimals and a split run on a whole cell still match. * fix(desktop): accept an older grader only when its index helper agrees The witness still matches a bundle whose evaluator is this REA's, or the older index expression alone when no path segment is a leading-zero number. A truncated verifier, a changed grader, or that older helper beside a segment such as 01 no longer counts as the same task. * fix(desktop): require the added record and leave save times out of list checks A record a selector names is checked itself, so its words have to be in that record. When an unnamed record only repeats words the seed already has, a list that holds a save time is checked by the text around that time. A later save of the same records still passes, and a missing or rewritten record fails. * fix(desktop): judge the older index helper by pointer segments only A leading zero in a file name or a URL does not change how the older index helper reads a pointer. The witness still rejects that helper when a pointer segment is a number such as 01. * fix(desktop): do not suggest list text the seed already passes A repeated record is shown by text the seed does not hold. The seed's own text is not a check. A pointer inside a check value is not a pointer segment for the older index helper. * fix(desktop): keep a linked settings file in the folder the link points at A selected ~/.config alias no longer moves MuseScore settings to that alias. The seed keeps settings/MuseScore or Documents, which is the path the export opens the note from. * fix(desktop): split home fetches by answer size and keep a size refusal A batch of tiny files stops before each path's envelope exceeds the host answer budget. A capture output past that ceiling stays a resource error instead of becoming a generic exit. * fix(desktop): seed a selected link under the path the app uses The selected spelling wins, so ~/.config/MuseScore is not rewritten to the folder it points at and the note stays the one launched document. A database wal and journal follow that database. A launch argument is respelled the same way. Teardown signals a detached PID only when its start identity still matches. * fix(desktop): keep a witness's actions and an incomplete checkpoint A failed witness save retries the action log it first recorded. A deletion left unconfirmed between the seed and the end is not reported as no change. Windows packs npm through a shell, which can start npm.cmd. * fix(desktop): read verifier pointers from the parsed checks A brace inside a check value is not an object boundary. A leading-zero pointer after that value still rejects the older index helper. * fix(desktop): prefer the most specific home spelling and retarget launch files A selected parent directory no longer hides a settings folder walked through a link. A launch filename under that folder is replaced with the seeded file's absolute path. * fix(desktop): pack the build runtime through npm's JavaScript entry npm pack and npm ci no longer spawn npm.cmd through a shell, so a temporary directory whose path contains spaces stays one argument. * fix(desktop): spell launch settings and keep a database log exact A database log matches only that file, so a neighboring folder is not moved. A launch option and the working directory use the same home spelling as the seed. * fix(desktop): move a state database's logs with the database The write-ahead log and journal follow the spelling the database received, including a walked state link. A neighboring folder stays put. A separate --config argument uses that spelling too. * fix(desktop): keep a selected file ahead of a database-log guess A file selected as itself keeps that spelling even when its name ends in -journal. Relative launch arguments are resolved in the captured working directory before that directory moves. * fix(desktop): keep outside-home database logs and option values A selected database outside the home keeps its write-ahead log. Launch options are rewritten only when they name a captured file or settings path. * fix(desktop): follow a database mapping and own limitation text A selected database keeps its log when a parent folder moves or the file sits outside the home. Trash and seed-lock tests compare the owning notice with the paths, and launch options that are not captured paths stay as written. * fix(desktop): retarget a settings folder that holds captured files A nested profile directory is a captured path when a seeded file is inside it. An option value that only resolves under the home stays as written. * fix(desktop): keep a program word and a directory's neighbor The program after env stays the program even when a captured file sits in a folder of that name. A selected directory is not a database, so a neighboring file keeps the parent folder's spelling. * fix(desktop): record whether a selected path is a directory Capture stores the walked path's kind. A neighboring file of a selected directory keeps the parent folder's spelling even when that directory never changes and its children are not content roots. * fix(desktop): mark containing paths without a pairwise scan A recorded path marks its known ancestors as directories in one walk up the path, instead of comparing every recorded path with every other. * fix(desktop): keep a selected folder that is named like a database log A folder the caller selected stays a selected root when its name ends in -journal or -wal. A generated log beside a database file still does not. * fix(desktop): refuse a build command that exceeds the argument vector Splitting one argument still leaves the whole command under Linux's E2BIG limit. A request past that budget is refused before the process starts. * fix(desktop): remap a captured path in an env assignment The program word stays the program. A NAME=value assignment keeps its name and follows a captured path value when that path's spelling moves. * fix(desktop): keep oversized text out of draft guards A value or line longer than the draft's text bound is not copied into a guard, so one large frame cannot fill the task by itself. * fix(desktop): keep an empty env value empty An empty assignment is not a path. Resolving it named the working directory and rewrote the value when that directory's spelling moved. * fix(desktop): check build runtime export capability * fix(desktop): provide complete runtime repack command * fix(desktop): retain runtime probe failures * test(desktop): identify capture independently of schema preflight * fix(desktop): preserve document URLs and value formats * fix(desktop): bound added checks and omit noisy text guards * fix(desktop): preserve launch URLs and JSON draft values * fix(desktop): recognize captured file URL documents * fix(desktop): render captured file URLs for runtime home * fix(desktop): distinguish phone numbers from save metadata * fix(desktop): preserve launch URLs and user text * fix(desktop): preserve local file URL authority * fix(desktop): preserve local file URL authority * fix(desktop): render captured file URLs at launch * fix(desktop): classify numeric timestamps using field context * fix(desktop): classify numeric timestamps using field context * fix(desktop): retain context for generated draft values * fix(desktop): retain context for generated draft values * test(desktop): cover generated IDs in text guards * test(desktop): cover generated IDs in text guards * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): retain clean text in noisy record fields * style(desktop): format the noisy-record draft files with the pinned oxfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): move launch execution to boundary suite * fix(desktop): redact build schema failure output * refactor(desktop): normalize schema failure once * fix(desktop): omit unsafe schema parser snippets * fix(desktop): preserve draft change and selected path evidence * test(desktop): group retained dconf note regressions * fix(desktop): respect archive entry format in draft checks * test(desktop): separate unowned-file draft note cases * docs(desktop): clarify task checks before scratch export * fix(desktop): respell selected paths in file URLs * test(desktop): group captured document spelling cases * fix(desktop): bound draft preview serialization * fix(desktop): restore selected state aliases * fix(desktop): respect entry format in draft noise * test(desktop): match exported alias evidence at its JSON boundary * style: fix desktop launch test formatting * style: format native command path schema * fix(desktop): map selected external launch paths * style(desktop): format seed document regressions * test(desktop): group launch URL regressions * fix(desktop): omit redundant nested state aliases * fix(desktop): compare added free text as a whole * fix(desktop): check recompressed seeds as shipped * fix(desktop): map captured launch paths once * refactor: remove unused whole-text guard state * refactor: stop passing unused text children * test: align free-text checks with whole-note policy * fix: validate recompressed desktop archive seeds * style(desktop): format archive seed regression * fix(desktop): redact runtime schema errors * fix(desktop): normalize captured file URLs * fix(desktop): report seeded files by capture path * fix(desktop): retain startup readiness failure stage * fix(desktop): retain JSON date checks * fix(desktop): preserve archive formatting checks * fix(desktop): preserve explicitly selected journal files * fix(desktop): report build command transport limits * style(desktop): format capture review fixes --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
536 lines
18 KiB
TypeScript
536 lines
18 KiB
TypeScript
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
|
import {
|
|
DESKTOP_EXPORT_FRAMEWORK_VERSION,
|
|
appModuleFile,
|
|
className,
|
|
exportedStateFiles,
|
|
launchDocumentLimitation,
|
|
renderAppClass,
|
|
renderEnvToml,
|
|
renderInstallScript,
|
|
renderReadme,
|
|
renderSkill,
|
|
renderSmokeTask,
|
|
type DesktopAppExportPlan,
|
|
type HomePathCollision,
|
|
type SeedScrubReport,
|
|
} from "../../domain/desktop/appExport.js";
|
|
import { INSTALL_SCRIPT } from "../../domain/desktop/appExportInstall.js";
|
|
import {
|
|
heldOpenLimitation,
|
|
leftOutLocksLimitation,
|
|
runtimeSeeds,
|
|
runtimeSeedsLimitation,
|
|
unownedChangedFolders,
|
|
unownedFoldersLimitation,
|
|
} from "../../domain/desktop/appExportUnowned.js";
|
|
import { installLimitations } from "../../domain/desktop/appExportInstallLimitations.js";
|
|
import type { DesktopApplicationCapture } from "../../domain/desktop/desktopCapture.js";
|
|
import {
|
|
desktopApplicationStateSchema,
|
|
versionAt,
|
|
type DesktopApplicationState,
|
|
} from "../../domain/desktop/desktopState.js";
|
|
import { isWithinAny } from "../../domain/desktop/desktopStateDiff.js";
|
|
import type { HostIdentity } from "../../domain/desktop/hostIdentity.js";
|
|
import { scrubDconf } from "../../domain/desktop/seedScrub.js";
|
|
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
|
import type { JsonValue } from "../../domain/jsonValue.js";
|
|
import {
|
|
inspectDesktopApplicationState,
|
|
readDesktopCapture,
|
|
type DesktopStateReaders,
|
|
} from "./DesktopApplicationState.js";
|
|
import {
|
|
DESKTOP_PROVIDER,
|
|
desktopOperationFailure,
|
|
} from "./DesktopCaptureRefusals.js";
|
|
import {
|
|
admitApplication,
|
|
exportEnvironmentName,
|
|
} from "./DesktopExportInstall.js";
|
|
import {
|
|
writeOutputTree,
|
|
writtenWithOpenHandles,
|
|
} from "./DesktopOutputTree.js";
|
|
import {
|
|
retainedCopies,
|
|
shippedSeedViews,
|
|
writeFiles,
|
|
type SeedVersion,
|
|
} from "./DesktopExportFiles.js";
|
|
import { withRetainedContent } from "./DesktopRetainedContent.js";
|
|
import { planLaunch, seedVersions } from "./DesktopExportLaunch.js";
|
|
import { selectStateEnds } from "./DesktopStateVersions.js";
|
|
import { admitDesktopTask, type AdmittedTask } from "./DesktopTaskExport.js";
|
|
|
|
const OPERATION = "export_desktop_application";
|
|
/** Largest seed file the export copies; the state view reads only 64 MiB. */
|
|
const SEED_MAX_BYTES = 1024 * 1024 * 1024;
|
|
|
|
/** What the caller asked to export, after CLI parsing. */
|
|
export interface DesktopExportRequest {
|
|
readonly capture: string;
|
|
readonly directory: string;
|
|
readonly name: string | undefined;
|
|
/** Task files to validate and add; a capture yields at most one. */
|
|
readonly tasks: readonly string[];
|
|
/** Where the computer downloads the captured package file from, for an application installed from one. */
|
|
readonly packageUrl?: string | undefined;
|
|
/** The checkpoint the seed is taken at; the baseline when omitted. */
|
|
readonly seedCheckpoint?: string | undefined;
|
|
/** The checkpoint a task's end state is read at; the last when omitted. */
|
|
readonly endCheckpoint?: string | undefined;
|
|
/** The seed was made for the task, as in a build computer, rather than taken from the user's own data. */
|
|
readonly syntheticSeed?: boolean | undefined;
|
|
}
|
|
|
|
/** What the export wrote. */
|
|
export interface DesktopExportResult {
|
|
readonly directory: string;
|
|
readonly environment: string;
|
|
readonly framework_version: string;
|
|
readonly checkpoints: { readonly seed: string; readonly end: string };
|
|
readonly paths: readonly string[];
|
|
readonly seed_files: readonly string[];
|
|
readonly unseeded_files: readonly string[];
|
|
/** Seed files rewritten to remove the capture host's name and user. */
|
|
readonly scrubbed_files: readonly string[];
|
|
/** gzip seed files compressed again only to clear their headers, their documents as captured. */
|
|
readonly recompressed_files: readonly string[];
|
|
/** Seed files that still hold them, in bytes the export does not rewrite or in their name. */
|
|
readonly unscrubbed_files: readonly string[];
|
|
readonly dconf_groups: number;
|
|
readonly files: readonly string[];
|
|
readonly limitations: readonly string[];
|
|
readonly task: AdmittedTask["summary"] | null;
|
|
}
|
|
|
|
const isRecord = (
|
|
value: JsonValue | null | undefined,
|
|
): value is Record<string, JsonValue> =>
|
|
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
|
|
/** The application's dconf groups at the seed, as a dconf key file with the identity scrubbed from its strings. */
|
|
const seedDconf = (
|
|
state: DesktopApplicationState,
|
|
seed: number,
|
|
identity: HostIdentity,
|
|
): { text: string; groups: number; holdsIdentity: boolean } => {
|
|
const database = state.paths.find(
|
|
(path) => path.format === "dconf" && path.role === "application_state",
|
|
);
|
|
const version =
|
|
database === undefined ? undefined : versionAt(database, seed);
|
|
const view = version?.view;
|
|
if (version?.present !== true || !isRecord(view) || !isRecord(view.groups))
|
|
return { text: "", groups: 0, holdsIdentity: false };
|
|
const groups = Object.keys(view.groups).length;
|
|
return { ...scrubDconf(view.groups, identity), groups };
|
|
};
|
|
|
|
type StatePath = DesktopApplicationState["paths"][number];
|
|
/** Files under the owned paths that existed at the seed without retained bytes, in the state view or omitted. */
|
|
const unseededFiles = (
|
|
capture: DesktopApplicationCapture,
|
|
homePath: (path: string) => string | null,
|
|
files: ReadonlyMap<string, StatePath>,
|
|
{ paths, seed }: { readonly paths: readonly string[]; readonly seed: number },
|
|
): readonly string[] => {
|
|
const listed = [...files]
|
|
.filter(([home, path]) => {
|
|
const version = versionAt(path, seed);
|
|
return (
|
|
isWithinAny(home, paths) &&
|
|
version?.present === true &&
|
|
version.sha256 === null
|
|
);
|
|
})
|
|
.map(([home]) => home);
|
|
const omitted = capture.state.omitted_content
|
|
.map(({ path }) => homePath(path))
|
|
.filter(
|
|
(home): home is string =>
|
|
home !== null && isWithinAny(home, paths) && !files.has(home),
|
|
);
|
|
return [...new Set([...listed, ...omitted])].sort();
|
|
};
|
|
|
|
/** Files in the desktop Trash at the seed, which the state view never makes the app's, so the seed leaves them out. */
|
|
const trashedFiles = (
|
|
files: ReadonlyMap<string, StatePath>,
|
|
seed: number,
|
|
): readonly string[] =>
|
|
[...files]
|
|
.filter(
|
|
([, path]) =>
|
|
path.reasons.includes("desktop_trash") &&
|
|
versionAt(path, seed)?.present === true,
|
|
)
|
|
.map(([home]) => home)
|
|
.sort();
|
|
|
|
/** Decide the bundle from the capture and its state view at the seed, with each seed's digest. */
|
|
const planExport = (
|
|
request: DesktopExportRequest,
|
|
capture: DesktopApplicationCapture,
|
|
state: DesktopApplicationState,
|
|
context: {
|
|
readonly evidenceId: string;
|
|
readonly seed: number;
|
|
readonly identity: HostIdentity;
|
|
},
|
|
): {
|
|
readonly plan: DesktopAppExportPlan;
|
|
readonly seeds: ReadonlyMap<string, SeedVersion>;
|
|
readonly limitations: readonly string[];
|
|
readonly collisions: readonly HomePathCollision[];
|
|
readonly files: ReadonlyMap<string, StatePath>;
|
|
readonly trashed: readonly string[];
|
|
readonly dconf: { readonly groups: number; readonly holdsIdentity: boolean };
|
|
} => {
|
|
const { application, host } = capture;
|
|
const source = exportEnvironmentName(capture, request.name);
|
|
const { install, windowClass } = admitApplication(
|
|
capture,
|
|
source,
|
|
request.packageUrl,
|
|
);
|
|
const electron = application.executable.electron_markers.length > 0;
|
|
const { homePath, stateAliases, files, collisions, paths, isLeftOutLock } =
|
|
exportedStateFiles(capture, state);
|
|
const { text: dconf, ...dconfScrub } = seedDconf(
|
|
state,
|
|
context.seed,
|
|
context.identity,
|
|
);
|
|
const { seeds, textSeeds, locks } = seedVersions(
|
|
files,
|
|
paths,
|
|
context.seed,
|
|
isLeftOutLock,
|
|
);
|
|
const unseeded = unseededFiles(capture, homePath, files, {
|
|
paths,
|
|
seed: context.seed,
|
|
});
|
|
const launch = planLaunch(capture, electron, seeds, files);
|
|
const plan: DesktopAppExportPlan = {
|
|
name: source,
|
|
className: className(source),
|
|
title: application.desktop_entry?.name ?? source,
|
|
aptPackage: install.aptPackage,
|
|
aptRelease: install.release,
|
|
packageVersion: application.package.version,
|
|
libraryPackages: install.libraryPackages,
|
|
aptSources: install.sources,
|
|
architectures: install.architectures,
|
|
packageFile: install.packageFile,
|
|
...(install.executablePackage === undefined
|
|
? {}
|
|
: { executablePackage: install.executablePackage }),
|
|
electron,
|
|
command: launch.command,
|
|
opens: launch.opens,
|
|
windowClass,
|
|
paths,
|
|
capturedHome: host.home,
|
|
seedCheckpoint: state.capture.checkpoints[context.seed] ?? "baseline",
|
|
syntheticSeed: request.syntheticSeed === true,
|
|
seedFiles: [...seeds.keys()].sort(),
|
|
textSeeds,
|
|
stateAliases,
|
|
unseededFiles: unseeded.filter((file) => !isLeftOutLock(file)),
|
|
leftOutLocks: [
|
|
...new Set([...locks, ...unseeded.filter(isLeftOutLock)]),
|
|
].sort(),
|
|
unownedFolders: unownedChangedFolders(files, paths),
|
|
runtimeSeeds: runtimeSeeds([...seeds.keys()]),
|
|
dconf,
|
|
captureEvidenceId: context.evidenceId,
|
|
};
|
|
const limitations = installLimitations(
|
|
install,
|
|
application.package,
|
|
electron,
|
|
);
|
|
return {
|
|
plan,
|
|
seeds,
|
|
limitations,
|
|
collisions,
|
|
files,
|
|
trashed: trashedFiles(files, context.seed),
|
|
dconf: dconfScrub,
|
|
};
|
|
};
|
|
|
|
/** The limitation naming files the desktop Trash held at the seed; none when it held none. */
|
|
export const trashedFilesLimitation = (
|
|
files: readonly string[],
|
|
): string | undefined =>
|
|
files.length === 0
|
|
? undefined
|
|
: `The desktop Trash held ${String(files.length)} file(s) at the seed checkpoint, which are not seeded: ${files.map((home) => `~/${home}`).join(", ")}. Restore one the task needs and capture again.`;
|
|
|
|
/** The limitation on where the seed came from: made for the task, or the user's real state, kept local. */
|
|
export const seedLimitation = (syntheticSeed: boolean): string =>
|
|
syntheticSeed
|
|
? "The seed was made for the task, not taken from a user's own data; read it before publishing the bundle."
|
|
: "The seed is the user's real state at the seed checkpoint; keep the bundle local.";
|
|
|
|
const SCRUB_LIMITATION =
|
|
"Binary state files are seeded as captured; only text files, UTF-8 or UTF-16 with a byte-order mark, and gzip documents, scrubbed inside, have the capture host's name, user@host and home path replaced. A gzip document so rewritten is compressed again as one member with no extra field, so a BGZF or dictzip file loses the blocks its index names.";
|
|
|
|
/** The bundle's generated files, the class module flagged when its dconf keys hold the identity, and its README, made once the seeds' scrub is known. */
|
|
const bundleText = (
|
|
plan: DesktopAppExportPlan,
|
|
admitted: AdmittedTask | undefined,
|
|
dconfHoldsIdentity: boolean,
|
|
) => {
|
|
const environment = `envs/${plan.name}`;
|
|
const text = (path: string, content: string, holdsIdentity = false) => ({
|
|
path,
|
|
bytes: Buffer.from(content),
|
|
holdsIdentity,
|
|
});
|
|
return {
|
|
readme: (scrub: SeedScrubReport) =>
|
|
text("README.md", renderReadme(plan, admitted?.readme, scrub)),
|
|
generated: [
|
|
text(`${environment}/env.toml`, renderEnvToml(plan)),
|
|
text(
|
|
`${environment}/${appModuleFile(plan.name)}`,
|
|
renderAppClass(plan),
|
|
dconfHoldsIdentity,
|
|
),
|
|
text(`${environment}/SKILL.md`, renderSkill(plan)),
|
|
...(plan.packageFile === null
|
|
? []
|
|
: [
|
|
text(
|
|
`${environment}/${INSTALL_SCRIPT}`,
|
|
renderInstallScript(plan.packageFile),
|
|
),
|
|
]),
|
|
text("tasks/smoke.json", renderSmokeTask(plan)),
|
|
...(admitted?.files ?? []).map((file) => text(file.path, file.content)),
|
|
],
|
|
};
|
|
};
|
|
|
|
const exportLimitations = (
|
|
capture: DesktopApplicationCapture,
|
|
plan: DesktopAppExportPlan,
|
|
facts: {
|
|
readonly install: readonly string[];
|
|
readonly collisions: readonly HomePathCollision[];
|
|
readonly identity: HostIdentity;
|
|
readonly trashed: readonly string[];
|
|
readonly files: ReadonlyMap<string, StatePath>;
|
|
},
|
|
): string[] => {
|
|
const opened = heldOpenLimitation(
|
|
capture.state.unretained_opened_directories,
|
|
capture.host.home,
|
|
plan.seedFiles.flatMap((seed) => {
|
|
const source = facts.files.get(seed)?.path;
|
|
return source === undefined ? [] : [{ seed, source }];
|
|
}),
|
|
);
|
|
const opens = launchDocumentLimitation(plan.opens);
|
|
const unowned = unownedFoldersLimitation(plan.unownedFolders);
|
|
const runtime = runtimeSeedsLimitation(plan.runtimeSeeds);
|
|
const locks = leftOutLocksLimitation(plan.leftOutLocks);
|
|
const trashed = trashedFilesLimitation(facts.trashed);
|
|
return [
|
|
seedLimitation(plan.syntheticSeed),
|
|
SCRUB_LIMITATION,
|
|
...(opens === undefined ? [] : [opens]),
|
|
...facts.install,
|
|
...(plan.unseededFiles.length === 0
|
|
? []
|
|
: [
|
|
`${String(plan.unseededFiles.length)} file(s) under the owned paths existed at the seed but were not retained, so they are not seeded.`,
|
|
]),
|
|
...(locks === undefined ? [] : [locks]),
|
|
...(unowned === undefined ? [] : [unowned]),
|
|
...(runtime === undefined ? [] : [runtime]),
|
|
...(trashed === undefined ? [] : [trashed]),
|
|
...(facts.identity.hostname === null || facts.identity.user === null
|
|
? [
|
|
"The capture does not record the host's name and user, so only the captured home is removed from the seed; capture again to remove them too.",
|
|
]
|
|
: []),
|
|
...(opened === undefined ? [] : [opened]),
|
|
...facts.collisions.map(
|
|
({ home, kept, dropped }) =>
|
|
`${dropped} and ${kept} both map to ~/${home}; the export uses ${kept} and leaves out ${dropped}.`,
|
|
),
|
|
];
|
|
};
|
|
|
|
const runExport = async (
|
|
request: DesktopExportRequest,
|
|
readers: DesktopStateReaders,
|
|
signal: AbortSignal | undefined,
|
|
) => {
|
|
const { evidence, capture } = await readDesktopCapture(
|
|
request.capture,
|
|
signal,
|
|
);
|
|
const stateEvidence = await inspectDesktopApplicationState(
|
|
request.capture,
|
|
readers,
|
|
signal,
|
|
);
|
|
if (stateEvidence instanceof AnalysisError) throw stateEvidence;
|
|
const state = desktopApplicationStateSchema.parse(
|
|
stateEvidence.normalized_result,
|
|
);
|
|
const { checkpoints } = state.capture;
|
|
const ends = selectStateEnds(
|
|
checkpoints,
|
|
{ seed: request.seedCheckpoint, end: request.endCheckpoint },
|
|
OPERATION,
|
|
);
|
|
const { home, hostname, user } = capture.host;
|
|
const identity = { home, hostname: hostname ?? null, user: user ?? null };
|
|
const { plan, seeds, collisions, files, trashed, dconf, ...install } =
|
|
planExport(request, capture, state, {
|
|
evidenceId: evidence.evidence_id,
|
|
seed: ends.seed,
|
|
identity,
|
|
});
|
|
const copies = retainedCopies(plan, seeds);
|
|
// A task's seed checks read the seeds as the bundle ships them, scrubbed.
|
|
const seedViews =
|
|
request.tasks.length === 0
|
|
? new Map()
|
|
: await withRetainedContent(
|
|
request.capture,
|
|
(content) => shippedSeedViews(content, copies, identity, signal),
|
|
SEED_MAX_BYTES,
|
|
);
|
|
const admitted = await admitDesktopTask(
|
|
request.tasks,
|
|
{
|
|
...plan,
|
|
files,
|
|
identity,
|
|
ends,
|
|
seedViews,
|
|
seeded: new Set(seeds.keys()),
|
|
},
|
|
signal,
|
|
);
|
|
const { generated, readme } = bundleText(plan, admitted, dconf.holdsIdentity);
|
|
let scrub: SeedScrubReport = {
|
|
scrubbed: [],
|
|
recompressed: [],
|
|
unscrubbed: [],
|
|
};
|
|
const unclosed = await withRetainedContent(
|
|
request.capture,
|
|
(content) =>
|
|
writeOutputTree(
|
|
request.directory,
|
|
async (tree) => {
|
|
const bundle = { generated, copies, identity, readme };
|
|
scrub = await writeFiles(tree, content, bundle, signal);
|
|
},
|
|
{ operation: OPERATION, field: "directory" },
|
|
signal,
|
|
),
|
|
SEED_MAX_BYTES,
|
|
);
|
|
const limitations = exportLimitations(capture, plan, {
|
|
install: install.limitations,
|
|
collisions,
|
|
identity,
|
|
trashed,
|
|
files,
|
|
});
|
|
const result: DesktopExportResult = {
|
|
directory: request.directory,
|
|
environment: plan.name,
|
|
framework_version: DESKTOP_EXPORT_FRAMEWORK_VERSION,
|
|
checkpoints: {
|
|
seed: checkpoints[ends.seed] ?? "baseline",
|
|
end: checkpoints[ends.end] ?? "baseline",
|
|
},
|
|
paths: plan.paths,
|
|
seed_files: plan.seedFiles,
|
|
unseeded_files: plan.unseededFiles,
|
|
scrubbed_files: [...scrub.scrubbed].sort(),
|
|
recompressed_files: [...scrub.recompressed].sort(),
|
|
unscrubbed_files: [...scrub.unscrubbed].sort(),
|
|
dconf_groups: dconf.groups,
|
|
files: [
|
|
"README.md",
|
|
...generated.map((file) => file.path),
|
|
...copies.map((copy) => copy.path),
|
|
],
|
|
limitations,
|
|
task: admitted?.summary ?? null,
|
|
};
|
|
return { result, captureEvidenceId: evidence.evidence_id, unclosed };
|
|
};
|
|
|
|
/** Export one capture folder as an agentenv computer app bundle, reported as Evidence. */
|
|
export const exportDesktopApplication = async (
|
|
request: DesktopExportRequest,
|
|
readers: DesktopStateReaders,
|
|
signal?: AbortSignal,
|
|
): Promise<Evidence | AnalysisError> => {
|
|
try {
|
|
const { result, captureEvidenceId, unclosed } = await runExport(
|
|
request,
|
|
readers,
|
|
signal,
|
|
);
|
|
const evidence = createEvidence(undefined, DESKTOP_PROVIDER, {
|
|
predicateType: "rea.desktop-application-export",
|
|
operation: OPERATION,
|
|
parameters: {
|
|
capture_evidence_id: captureEvidenceId,
|
|
named: request.name !== undefined,
|
|
tasks: request.tasks.length,
|
|
package_url: request.packageUrl !== undefined,
|
|
seed_checkpoint: request.seedCheckpoint ?? null,
|
|
end_checkpoint: request.endCheckpoint ?? null,
|
|
synthetic_seed: request.syntheticSeed === true,
|
|
},
|
|
result: {
|
|
...result,
|
|
checkpoints: { ...result.checkpoints },
|
|
paths: [...result.paths],
|
|
seed_files: [...result.seed_files],
|
|
unseeded_files: [...result.unseeded_files],
|
|
scrubbed_files: [...result.scrubbed_files],
|
|
recompressed_files: [...result.recompressed_files],
|
|
unscrubbed_files: [...result.unscrubbed_files],
|
|
files: [...result.files],
|
|
limitations: [...result.limitations],
|
|
},
|
|
confidence: "derived",
|
|
authority: "analyst-inference",
|
|
limitations: [...result.limitations],
|
|
});
|
|
return unclosed === undefined
|
|
? evidence
|
|
: writtenWithOpenHandles(
|
|
{
|
|
provider: DESKTOP_PROVIDER.id,
|
|
operation: OPERATION,
|
|
what: "bundle",
|
|
},
|
|
request.directory,
|
|
unclosed,
|
|
evidence,
|
|
);
|
|
} catch (cause: unknown) {
|
|
return desktopOperationFailure(cause, signal, OPERATION, "Desktop export");
|
|
}
|
|
};
|