Files
reverse-engineering-anything/src/application/desktop/DesktopCaptureScope.ts
T
morlutoandCursor Agent 9f5f9c1289 fix(desktop): preserve capture evidence and output ownership (#9899)
* fix(desktop): retain capture identity and cleanup ownership

* fix(desktop): validate destinations and finish inputs before export

* fix(desktop): preserve package ownership and apt trust boundaries

* fix(sqlite): preserve observed facts and distinguish special real values

* fix(desktop): bind computer files to data-object metadata

* test(desktop): count the tagged negative-zero cell spelling

SQLite view cells encode negative zero as a real object so it stays
distinct from the text "-0". The byte budget follows that spelling.

* fix(desktop): keep unresolved discovered state directories

Canonicalizing an unreadable path or dangling symlink aborted capture
before the inventory could record that the path was unknown. Those
discovered directories now keep their absolute spelling in the scope.

* test(desktop): keep the capture scope suite within its line limit

The unresolved state-directory case lives beside the suite so the
existing callback stays within the lint limit.

* fix(desktop): retain cancellation through capture input cleanup

* fix(desktop): avoid reserved Pydantic settings properties

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-11-11 17:36:47 +08:00

180 lines
6.2 KiB
TypeScript

import { lstat } from "node:fs/promises";
import { basename, isAbsolute } from "node:path";
import type { DesktopApplicationInventory } from "../../domain/desktop/desktopCapture.js";
import { isWithinAny } from "../../domain/desktop/desktopStateDiff.js";
import { SQLITE_SIDECARS } from "../../domain/desktop/stateFormats.js";
import type { WindowMatching } from "../../desktop/DesktopSessionObservations.js";
import { absoluteCallerPath } from "../../filesystem/callerPath.js";
import { canonicalCallerPath } from "../../filesystem/canonicalCallerPath.js";
import type { CheckpointScope } from "./DesktopCheckpointRecorder.js";
const unique = (paths: readonly string[]) => [...new Set(paths)];
/** A discovered state path whose physical file cannot be established. */
const unresolvedStateDirectory = (cause: unknown): boolean => {
const code = (cause as NodeJS.ErrnoException).code;
return (
code === "ENOENT" ||
code === "EACCES" ||
code === "EPERM" ||
code === "ENOTDIR" ||
code === "ELOOP"
);
};
/**
* Canonicalize a discovered state directory when the filesystem can. An
* unreadable path or dangling symlink stays the discovered absolute path so
* the capture can publish that unknown instead of aborting.
*/
const canonicalStateDirectory = async (path: string): Promise<string> => {
try {
return await canonicalCallerPath(path);
} catch (cause: unknown) {
if (!unresolvedStateDirectory(cause)) throw cause;
return absoluteCallerPath(path);
}
};
/** Whether the walked path is a directory. A missing path is not one, matching the sidecar decision. */
const pathKind = async (path: string): Promise<"file" | "directory"> =>
(await lstat(path).then(
(stats) => stats.isDirectory(),
(cause: unknown) => {
if ((cause as NodeJS.ErrnoException).code === "ENOENT") return false;
throw cause;
},
))
? "directory"
: "file";
/** A path the caller selected, absolute as named, and the physical path walked for it. */
export interface SelectedPath {
readonly path: string;
readonly physical: string;
/** The walked path's kind, so a later export does not infer a directory from changes. */
readonly kind: "file" | "directory";
}
/** The checkpoint scope, the selected paths in it, and absolute arguments too broad to be part of it. */
export interface CaptureScope {
readonly scope: CheckpointScope;
/** `--state-path` values, then absolute arguments, in the scope. */
readonly selectedPaths: readonly SelectedPath[];
/** `/` or a directory containing the home directory, named by `--argument`. */
readonly broadArguments: readonly string[];
}
/**
* Paths in their physical spelling, so walks and exclusions agree; a selected
* path keeps the spelling it was named by too, which a link would lose. An
* absolute argument becomes a content root unless it is `/` or contains the
* home directory, which would retain and walk whole trees. A selected path
* that is not a directory brings its SQLite sidecars as content roots too.
*/
export const captureScope = async (
request: {
readonly arguments: readonly string[];
readonly statePaths: readonly string[];
readonly excludes: readonly string[];
readonly maxEntries: number;
},
inventory: DesktopApplicationInventory,
home: string,
output: string,
): Promise<CaptureScope> => {
const canonical = (paths: readonly string[]) =>
Promise.all(paths.map((path) => canonicalCallerPath(path)));
const named = (paths: readonly string[]) =>
Promise.all(
paths.map(async (path) => ({
path: absoluteCallerPath(path),
physical: await canonicalCallerPath(path),
})),
);
const stateDirectories = await Promise.all(
inventory.state_directories.map((entry) =>
canonicalStateDirectory(entry.path),
),
);
const argumentPaths = await named(
request.arguments.filter((value) => isAbsolute(value)),
);
const broadArguments = unique(
argumentPaths
.map(({ physical }) => physical)
.filter((path) => isWithinAny(home, [path])),
);
const selectedPaths = await Promise.all(
[
...new Map(
[
...(await named(request.statePaths)),
...argumentPaths.filter(
({ physical }) => !broadArguments.includes(physical),
),
].map((entry) => [entry.path, entry]),
).values(),
].map(async (entry) => ({
...entry,
kind: await pathKind(entry.physical),
})),
);
const selected = unique(selectedPaths.map(({ physical }) => physical));
// A database selected on its own is unreadable without its logs. A directory
// is not a database, so a neighbor named like a log stays a normal file.
const contentRoots = unique([
...stateDirectories,
...selected,
...selectedPaths.flatMap(({ physical, kind }) =>
kind === "directory"
? []
: SQLITE_SIDECARS.map(({ suffix }) => `${physical}${suffix}`),
),
]);
return {
scope: {
roots: unique([
home,
...contentRoots.filter((path) => !isWithinAny(path, [home])),
]),
contentRoots,
stateDirectories,
excluded: unique([output, ...(await canonical(request.excludes))]),
maxEntries: request.maxEntries,
},
selectedPaths,
broadArguments,
};
};
/**
* Window names that mark a window as the application's: the entry's
* `StartupWMClass`, its full id and last id part, the executable's name and a
* flatpak's application id. A flatpak's window pids are sandbox pids, so its
* windows are matched by name only.
*/
export const applicationWindowMatching = (
inventory: DesktopApplicationInventory,
): WindowMatching => {
const flatpak = inventory.package.kind === "flatpak";
const executable = basename(inventory.executable.path);
return {
names: new Set(
[
inventory.desktop_entry?.startup_wm_class,
flatpak && executable === "flatpak" ? null : executable,
inventory.desktop_entry?.id,
inventory.desktop_entry?.id?.split(".").at(-1),
flatpak ? inventory.package.name : null,
]
.filter(
(name): name is string => typeof name === "string" && name.length > 0,
)
.map((name) => name.toLowerCase()),
),
byPid: !flatpak,
};
};