Files
rea/src/application/desktop/DesktopTaskDraftNotes.test.ts
T
012861ce1d feat(desktop): draft child-text selectors, member counts and attribute text, and fold in a third batch's findings (#9132)
* 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.

* test(desktop): pass the selected log into the draft

The export's selected home paths decide which log stays in the draft.
The line-guard test now names that log instead of relying on its reason.

* 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.

* docs(desktop): correct dconf and check-preview guidance

A dconf version kept without its bytes is unreadable, not an empty key
list. A values preview is copied into a check only when it is an uncut scalar.

* 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): keep a run's font on the run, not the frame's text

A formatting attribute such as Scribus FONT is not the document's words.
Joining it across runs made a frame-wide text check of ItalicBold that
failed when a run was split. The font stays a value check on its own run.

* fix(desktop): do not pair JSON records by a selector-shaped field

A field named @record_id matched the id suffix and became [@record_id=one],
which reads an XML attribute. Records paired while their pointers matched
nothing. Names that start with @ or > are not id fields.

* fix(desktop): count a save-numbered id once when pairing members

xml:id and draw:id values such as id123456 were both generated and
numbered, so the same selector was counted twice and refused. A text
edit of two elements keyed only by those ids now keeps its check.

* fix(desktop): preserve selected state directory aliases

* fix(desktop): align nested state selections with aliases

* 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): exclude unseeded locks from task checks

* fix(desktop): preserve draft bounds and launch URLs

* fix(desktop): render draft values using their source format

* 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 captured URLs and user text

* fix(desktop): preserve local file URL authority

* 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): classify numeric timestamps using field context

* fix(desktop): retain context for generated draft values

* 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

* 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): isolate launcher URL encoding

* fix(desktop): retain clean text in noisy record fields

* fix(desktop): classify added line values in one pass

* fix(desktop): apply XML quote rules to text drafts

* fix(desktop): distinguish XML attributes from quoted text

* fix(desktop): preserve parsed XML line context

* fix(desktop): retain partial XML syntax facts

* fix(desktop): recognize markdown autolinks in drafts

* fix(desktop): reuse export exclusions in task drafts

* docs(desktop): clarify gzip scrub limits

* 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

* fix(desktop): preserve explicitly selected journal documents

* fix(xml): avoid scanning selected ancestors per tag

* fix(desktop): exclude covered text runs from draft counts

* fix: preserve text when drafting desktop checks

* fix: restore nested desktop state aliases

* refactor: share UUID recognition across draft checks

* fix: retain multiline XML attribute context

* fix: retain relationship identifiers in task drafts

* docs: clarify desktop draft identifier handling

* test(desktop): type formatting run cases as pairs

* test(desktop): separate markup boundary regression group

* 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

* fix(desktop): retain app state logs in exported seeds

* fix: align desktop numeric seed comparisons

* test(desktop): keep one draft exclusion fixture import

* test(desktop): retain log eligibility across draft test groups

* 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

* docs(desktop): clarify recovered seed format

* test(desktop): group shipped gzip seed checks

* fix: retain quoted identifier text in task drafts

* fix: recognize Unicode XML in desktop state readers

* fix(desktop): bound nested draft checks

* fix(desktop): explain missing arrays in truncated views

* fix(desktop): find XML type references in archives

* test(desktop): remove duplicated capture assertions

* fix(desktop): retain nested omitted text boundaries

* style(desktop): format draft value imports

* test(desktop): group model and draft value checks

* 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): retain placed-item sibling guards

* 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

* docs(desktop): clarify unreadable dconf versions

* 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>
2026-11-09 22:56:44 +08:00

413 lines
13 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import type {
DesktopApplicationCapture,
DesktopStateChange,
} from "../../domain/desktop/desktopCapture.js";
import type { DesktopStateReaders } from "./DesktopApplicationState.js";
import { draftDesktopApplicationTask } from "./DesktopTaskDraft.js";
import {
EDITED_NOTE,
HOME,
NOTE,
SAVED_NOTE,
change,
readers,
retained,
seedEndCapture,
writeCaptureFolder,
} from "./desktopCapture.fixture.js";
const ENDS = { seed: "seed", end: "end" };
const draftSchema = z.looseObject({
files: z.array(z.unknown()),
notes: z.array(
z.looseObject({
code: z.string(),
files: z
.array(z.object({ file: z.string(), role: z.string() }))
.optional(),
more: z.int().optional(),
error: z.string().optional(),
}),
),
});
/** The draft's notes for a capture, between seed and end. */
const notesOf = async (
recorded: DesktopApplicationCapture,
extraContent: readonly (string | Buffer)[] = [],
stateReaders: DesktopStateReaders = readers,
) => {
const result = await draftDesktopApplicationTask(
await writeCaptureFolder(recorded, undefined, [
EDITED_NOTE,
...extraContent,
]),
stateReaders,
undefined,
ENDS,
);
if (result instanceof Error) throw result;
return draftSchema.parse(result.normalized_result);
};
/** The seed-and-end capture with the `end` checkpoint replaced. */
const withEnd = (
base: DesktopApplicationCapture,
end: {
changes: DesktopStateChange[];
kept: ReturnType<typeof retained>[];
},
): DesktopApplicationCapture => ({
...base,
state: {
...base.state,
checkpoints: base.state.checkpoints.map((point) =>
point.name === "end"
? { ...point, changes: end.changes, retained: end.kept }
: point,
),
},
});
const database = `${HOME}/.config/dconf/user`;
// dconf databases by the keys they hold; the reader dumps each as dconf does.
const dumps: Readonly<Record<string, string>> = {
"GVariant wrap=false": "[org/example/notes]\nwrap=false\n",
"GVariant wrap=true": "[org/example/notes]\nwrap=true\n",
"GVariant wallpaper=blue":
"[org/example/notes]\nwrap=false\n\n[org/gnome/desktop/background]\ncolor='blue'\n",
"GVariant desktop only": "[org/gnome/desktop/background]\ncolor='blue'\n",
};
const dconfReaders: DesktopStateReaders = {
...readers,
dconf: async (path) => {
const dump = dumps[await readFile(path, "latin1")];
return dump === undefined
? { ok: false, error: "not a fixture database" }
: { ok: true, text: dump };
},
};
describe("draftDesktopApplicationTask notes", () => {
it("has none when the draft has files", async () => {
const draft = await notesOf(seedEndCapture());
expect(draft.files).toHaveLength(1);
expect(draft.notes).toEqual([]);
});
it("passes on a drafted file's own notes, such as a document REA reads as binary", async () => {
const [before, after] = [1, 2].map((version) =>
Buffer.from([0x1f, 0x8b, 0x08, 0x00, version]),
);
if (before === undefined || after === undefined) throw new Error("fixture");
const base = seedEndCapture();
const compressed: DesktopApplicationCapture = {
...base,
state: {
...base.state,
checkpoints: base.state.checkpoints.map((point) =>
point.name === "seed"
? {
...point,
changes: [change(NOTE, { after: before })],
retained: [retained(NOTE, before)],
}
: point.name === "end"
? {
...point,
changes: [change(NOTE, { before, after })],
retained: [retained(NOTE, after)],
}
: point,
),
},
};
const draft = await notesOf(compressed, [before, after]);
expect(draft.files).toHaveLength(1);
expect(draft.notes).toEqual([
expect.objectContaining({
code: "unreadable_view",
file: "Documents/today.txt",
}),
]);
});
it("says no file changed between seed and end when none did", async () => {
const draft = await notesOf(
withEnd(seedEndCapture(), { changes: [], kept: [] }),
);
expect(draft.files).toEqual([]);
// The window title named the note, so the capture recognized a document.
expect(draft.notes.map(({ code }) => code)).toEqual(["no_change"]);
});
it("does not call reordered saved lines unchanged when the value diff is empty", async () => {
const base = seedEndCapture();
const note = `${HOME}/Documents/today.txt`;
const before = "milk\neggs\n";
const after = "eggs\nmilk\n";
const capture = {
...base,
state: {
...base.state,
checkpoints: base.state.checkpoints.map((point) =>
point.name === "seed"
? {
...point,
changes: [change(note, { after: before })],
retained: [retained(note, before)],
}
: point.name === "end"
? {
...point,
changes: [change(note, { before, after })],
retained: [retained(note, after)],
}
: point,
),
},
};
const draft = await notesOf(capture, [before, after]);
expect(draft.files).toEqual([]);
expect(draft.notes.map(({ code }) => code)).not.toContain("no_change");
expect(draft.notes.map(({ code }) => code)).toContain(
"uncheckable_changes",
);
});
it("does not call an empty change list unchanged when a checkpoint was cut short", async () => {
const base = withEnd(seedEndCapture(), { changes: [], kept: [] });
const cut: DesktopApplicationCapture = {
...base,
state: {
...base.state,
checkpoints: base.state.checkpoints.map((point) =>
point.name === "end" ? { ...point, truncated: true } : point,
),
},
};
const draft = await notesOf(cut);
expect(draft.notes.map(({ code }) => code)).toContain("incomplete_capture");
expect(draft.notes.map(({ code }) => code)).not.toContain("no_change");
});
it("does not call the ends unchanged when a checkpoint between them left a deletion unconfirmed", async () => {
const base = withEnd(seedEndCapture(), { changes: [], kept: [] });
const seedAt = base.state.checkpoints.findIndex(
(point) => point.name === "seed",
);
const seed = base.state.checkpoints[seedAt];
if (seed === undefined) throw new Error("the fixture has a seed");
const partial: DesktopApplicationCapture = {
...base,
state: {
...base.state,
checkpoints: [
...base.state.checkpoints.slice(0, seedAt + 1),
{
...seed,
name: "during",
trigger: "request",
unconfirmed_changes: 1,
changes: [],
},
...base.state.checkpoints.slice(seedAt + 1),
],
},
};
const draft = await notesOf(partial);
expect(draft.notes.map(({ code }) => code)).toContain("incomplete_capture");
expect(draft.notes.map(({ code }) => code)).not.toContain("no_change");
});
});
describe("draftDesktopApplicationTask notes for unowned files", () => {
it("lists the first five changed files outside the owned paths, desktop files last, when no document was recognized", async () => {
const base = seedEndCapture();
const untitled: DesktopApplicationCapture = {
...base,
session: {
...base.session,
windows: base.session.windows.map((window) => ({
...window,
titles: ["Shopping - Notes"],
})),
},
};
const note = `${HOME}/Documents/today.txt`;
const others = ["a", "b", "c", "d", "e"].map(
(name) => `${HOME}/Music/${name}.txt`,
);
const fonts = `${HOME}/.cache/fontconfig/cache-1`;
const draft = await notesOf(
withEnd(untitled, {
changes: [
change(note, { before: SAVED_NOTE, after: EDITED_NOTE }),
...[fonts, ...others].map((path) => change(path, { after: "x\n" })),
],
kept: [
retained(note, EDITED_NOTE),
...[fonts, ...others].map((path) => retained(path, "x\n")),
],
}),
["x\n"],
);
expect(draft.files).toEqual([]);
expect(draft.notes.map(({ code }) => code)).toEqual([
"unowned_changes",
"no_document",
]);
const [unowned] = draft.notes;
expect(unowned?.files).toEqual([
{ file: "Documents/today.txt", role: "unrelated" },
...["a", "b", "c", "d"].map((name) => ({
file: `Music/${name}.txt`,
role: "unrelated",
})),
]);
// Music/e.txt and the shared font cache are counted, not listed.
expect(unowned?.more).toBe(2);
});
});
describe("draftDesktopApplicationTask notes for retained dconf state", () => {
it("says a change the app saved only in dconf is one no check reads, rather than that nothing changed", async () => {
/** The seed-and-end capture whose only change from seed to end is the dconf database's, to `after`. */
const savedInDconf = (after: string): DesktopApplicationCapture => {
const ended = withEnd(seedEndCapture(), {
changes: [change(database, { before: "GVariant wrap=false", after })],
kept: [retained(database, after)],
});
const [baseline, ...later] = ended.state.checkpoints;
if (baseline === undefined) throw new Error("the fixture has a baseline");
return {
...ended,
state: {
...ended.state,
checkpoints: [
{
...baseline,
retained: [
...baseline.retained,
retained(database, "GVariant wrap=false"),
],
},
...later,
],
},
};
};
const saved = await notesOf(
savedInDconf("GVariant wrap=true"),
Object.keys(dumps),
dconfReaders,
);
const desktop = await notesOf(
savedInDconf("GVariant wallpaper=blue"),
Object.keys(dumps),
dconfReaders,
);
// The reader fails on this database, as it does when dconf-cli is missing.
const unread = await notesOf(
savedInDconf("GVariant unknown"),
[...Object.keys(dumps), "GVariant unknown"],
dconfReaders,
);
expect(saved.files).toEqual([]);
expect(saved.notes.map(({ code }) => code)).toEqual([
"uncheckable_changes",
]);
expect(saved.notes[0]?.files).toEqual([
{ file: ".config/dconf/user", role: "application_state" },
]);
// Desktop-only changes do not establish that no file changed.
expect(desktop.notes.map(({ code }) => code)).toEqual([
"uncheckable_changes",
]);
// A database REA could not read changed: whose keys is unknown, and the read error is kept.
expect(unread.notes).toMatchObject([
{
code: "unreadable_changes",
files: [{ file: ".config/dconf/user", role: "application_state" }],
error: "not a fixture database",
},
]);
});
});
describe("draftDesktopApplicationTask notes on a dconf database the capture kept no copy of", () => {
it("keeps a dconf database unknown when the capture kept no copy of its starting bytes", async () => {
/** As the recorder writes it: the first walk keeps no copy of the database, so its change has no starting digest. */
const unkept = (after: string): DesktopApplicationCapture => {
const written = change(database, {
before: "GVariant wrap=false",
after,
});
return withEnd(seedEndCapture(), {
changes: [
{
...written,
before:
written.before === null
? null
: { ...written.before, sha256: null },
},
],
kept: [retained(database, after)],
});
};
const saved = await notesOf(
unkept("GVariant wrap=true"),
Object.keys(dumps),
dconfReaders,
);
const desktop = await notesOf(
unkept("GVariant desktop only"),
Object.keys(dumps),
dconfReaders,
);
expect(saved.notes.map(({ code }) => code)).toEqual(["unreadable_changes"]);
expect(saved.notes[0]?.error).toContain("content not retained");
expect(saved.notes[0]?.files).toEqual([
{ file: ".config/dconf/user", role: "application_state" },
]);
expect(desktop.notes.map(({ code }) => code)).toEqual([
"unreadable_changes",
]);
});
});
describe("draftDesktopApplicationTask notes for an incomplete checkpoint", () => {
it("does not call an empty change list unchanged when a checkpoint omits how many paths it left unchecked", async () => {
const base = withEnd(seedEndCapture(), { changes: [], kept: [] });
const omitted: DesktopApplicationCapture = {
...base,
state: {
...base.state,
checkpoints: base.state.checkpoints.map((point) => {
const { unchecked_paths: _dropped, ...rest } = point;
return rest;
}),
},
};
const draft = await notesOf(omitted);
expect(draft.notes.map(({ code }) => code)).toContain("incomplete_capture");
expect(draft.notes.map(({ code }) => code)).not.toContain("no_change");
});
});