chore: merge captured main into iNES container support

This commit is contained in:
morluto
2026-10-13 21:45:12 +08:00
252 changed files with 12483 additions and 1405 deletions
@@ -0,0 +1,85 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"retains getter-local alias mutations in exported Evidence through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-getter-local-aliases-");
const cases = [
["initialized", "const self = this; return self.s;", true],
["assigned", "let self; self = this; return self.s;", true],
["destructured", "const { s: value } = this; return value;", true],
["readOnly", "const self = this; return self.s;", false],
[
"cyclic",
"let self = this.start; while (flag) self = self.child; return self;",
true,
"start: { child: { child: shared } }",
],
] as const;
const privateCases = [
["privateProjection", "shared", true, "unknown"],
["privateUnrelated", "{ peer: shared }", true, "literal"],
["privateReadOnly", "shared", false, "literal"],
] as const;
await writeFile(
join(root, "app.mjs"),
cases
.map(
([
name,
getter,
write,
members = "s: shared",
]) => `export function ${name}() {
const shared = { x: 1 };
const box = { ${members}, get v() { ${getter} } };
${write ? "box.v.x = 2;" : "const saved = box.v;"}
return shared.x;
}`,
)
.join("\n") +
privateCases
.map(
([name, value, write]) => `export function ${name}() {
const shared = { x: 1 };
class Box {
#s = ${value};
peer = this;
get v() { const { peer: self } = this; return self.#s; }
}
const box = new Box();
${write ? "box.v.x = 2;" : "const saved = box.v;"}
return shared.x;
}`,
)
.join("\n"),
);
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
for (const [name, status] of [
...cases.map(([name, , write]) => [name, write ? "unknown" : "literal"]),
...privateCases.map(([name, , , status]) => [name, status]),
]) {
const observation = graph.nodes
.flatMap(({ observations }) => observations)
.find(
({ properties }) =>
properties.semantic_role === "export-return-shapes" &&
properties.exported_name === name,
);
expect(observation, name).toBeDefined();
expect(observation?.properties.static_return_shapes).toMatchObject([
{
value_status: status,
fields: [
{ path: "", state: status, value: status === "unknown" ? null : 1 },
],
},
]);
}
},
);
@@ -39,6 +39,47 @@ export function superclass() {
new B().v.x = 2;
return shared.x;
}
export function arrayReceiver() {
const arr = [{ x: 1, get self() { return this; } }];
arr[0].self.x = 2;
return arr[0].x;
}
export function nestedArrayReceiver() {
const outer = { arr: [{ x: 1, get self() { return this; } }] };
outer.arr[0].self.x = 2;
return outer.arr[0].x;
}
export function assignedReceiver() {
let box;
box = { x: 1, get self() { return this; } };
box.self.x = 2;
return box.x;
}
export function savedArrayReceiver() {
const arr = [{ x: 1, get self() { return this; } }];
const saved = arr[0].self;
saved.x = 2;
return arr[0].x;
}
export function arrayReadOnly() {
const arr = [{ x: 1, get self() { return this; } }];
const saved = arr[0].self;
return arr[0].x;
}
export function replacementKeepsOldObject() {
const old = { x: 1 };
let box = old;
box = { x: 1, old: box, get self() { return this; } };
box.self.x = 2;
return old.x;
}
export function replacementMutatesCapturedObject() {
const old = { x: 1 };
let box = old;
box = { old: box, get self() { return this; } };
box.self.old.x = 2;
return old.x;
}
export function untouched() {
const box = { x: 1, y: 1, get self() { return this; } };
box.self.y = 2;
@@ -66,13 +107,20 @@ export function untouched() {
const { graph } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(document).normalized_result;
for (const name of [
"self",
"property",
"privateField",
"superclass",
"untouched",
]) {
for (const [name, status] of [
["self", "unknown"],
["property", "unknown"],
["privateField", "unknown"],
["superclass", "unknown"],
["arrayReceiver", "unknown"],
["nestedArrayReceiver", "unknown"],
["assignedReceiver", "unknown"],
["savedArrayReceiver", "unknown"],
["arrayReadOnly", "literal"],
["replacementKeepsOldObject", "literal"],
["replacementMutatesCapturedObject", "unknown"],
["untouched", "literal"],
] as const) {
const projection = graph.nodes
.flatMap(({ observations }) => observations)
.find(
@@ -82,7 +130,16 @@ export function untouched() {
);
expect(projection, name).toBeDefined();
expect(projection?.properties.static_return_shapes).toMatchObject([
{ value_status: name === "untouched" ? "literal" : "unknown" },
{
value_status: status,
fields: [
{
path: "",
state: status,
...(status === "literal" ? { value: 1 } : {}),
},
],
},
]);
}
},
@@ -141,6 +141,13 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
).toBe("node_modules/fi%xture/actual.cjs");
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
expect(graph.coverage.status).toBe("complete");
const requireFileUrl = graph.edges.find(
({ properties }) =>
properties.module_link_kind === "require" &&
properties.specifier === "file:///src/uri-dep.cjs",
);
expect(requireFileUrl?.evidence.limitations.length).toBeGreaterThan(0);
const imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
@@ -0,0 +1,111 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect } from "vitest";
import {
CPU,
fatImage,
machoImage,
} from "../../src/artifacts/apple/MachoImage.fixture.js";
import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest.for(["jar", "zip"])(
"distinguishes JVM classes from universal Mach-O files in %s inventory",
async (extension, { cli }) => {
const root = await createTestTempDirectory("rea-class-inventory-");
const path = join(root, `mixed.${extension}`);
// The large class can hold the entire 65-entry table suggested by its
// version bytes. Checking only the table length does not distinguish it.
const classes = [
["Hello.class", javaClass()],
["Big.class", javaClass("x".repeat(4_000))],
["renamed.bin", javaClass()],
] as const;
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const [name, bytes] of classes)
await writer.add(name, new Uint8ArrayReader(bytes));
const nativePaths: string[] = [];
for (const wide of [false, true]) {
for (const littleEndian of [false, true]) {
const name = `fat${wide ? 64 : 32}-${littleEndian ? "le" : "be"}`;
nativePaths.push(name);
await writer.add(
name,
new Uint8ArrayReader(
fatImage(
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
wide,
littleEndian,
),
),
);
}
}
await writeFile(path, await writer.close());
const reply = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(reply.exitCode, reply.stdout + reply.stderr).toBe(0);
const inspection = artifactInspectionResultSchema.parse(
parseEvidence(reply.json).normalized_result,
);
const inventory = artifactInventoryResultSchema.parse(
inspection.substeps[0]?.evidence.normalized_result,
);
for (const name of nativePaths) {
expect(inventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: name,
artifact_kind: "executable",
artifact_format: "mach-o-universal",
limitations: [],
}),
);
}
for (const [name, bytes] of classes) {
const occurrence = inventory.occurrences.find(
(item) => item.logical_path === name,
);
expect(occurrence).toBeDefined();
expect.soft(occurrence?.artifact_kind, name).not.toBe("executable");
expect.soft(occurrence?.artifact_format, name).not.toMatch(/^mach-o/u);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const node = inventory.nodes.find((item) => item.sha256 === sha256);
expect(node).toBeDefined();
expect.soft(node?.format, name).not.toMatch(/^mach-o/u);
}
},
);
/** Minimal valid Java 21 class, with an optional unused UTF-8 constant. */
const javaClass = (extra?: string): Buffer => {
const utf8 = (value: string): Buffer => {
const text = Buffer.from(value);
const header = Buffer.alloc(3);
header[0] = 1;
header.writeUInt16BE(text.length, 1);
return Buffer.concat([header, text]);
};
const constants = [
Buffer.from([7, 0, 2]),
utf8("Hello"),
Buffer.from([7, 0, 4]),
utf8("java/lang/Object"),
...(extra === undefined ? [] : [utf8(extra)]),
];
const header = Buffer.from("cafebabe000000410000", "hex");
header.writeUInt16BE(constants.length + 1, 8);
return Buffer.concat([
header,
...constants,
Buffer.from("0021000100030000000000000000", "hex"),
]);
};
+106 -1
View File
@@ -1,5 +1,5 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
@@ -8,6 +8,111 @@ import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest.for([
{
label: "blank defaults",
harness: "",
agents: " \t ",
dshRoot: "home/.dsh",
agentsRoot: "home/.agents",
},
{
label: "tilde roots",
harness: "~/selected harness",
agents: "~\\shared agents",
dshRoot: "home/selected harness",
agentsRoot: "home/shared agents",
},
{
label: "relative roots",
harness: "./selected harness",
agents: "../shared agents",
dshRoot: "workspace/selected harness",
agentsRoot: "shared agents",
},
])(
"DSH CLI uses Harness path semantics through setup, doctor and uninstall for $label",
async ({ harness, agents, dshRoot, agentsRoot }, { cli }) => {
const root = await createTestTempDirectory("rea-dsh-paths-");
const home = join(root, "home");
const cwd = join(root, "workspace");
const config = join(root, dshRoot, "cordis.patch.yml");
const skillRoot = join(
root,
agentsRoot,
"skills",
"reverse-engineer-anything",
);
const skill = join(skillRoot, "SKILL.md");
await mkdir(home);
await mkdir(cwd);
await mkdir(dirname(config), { recursive: true });
const original =
"# caller patch\n- insert: [{id: caller, name: caller-plugin}]\n";
await writeFile(config, original);
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd,
environment: {
HOME: home,
USERPROFILE: home,
DSH_HOME: harness,
DSH_AGENTS_HOME: agents,
},
});
const planned = await run(["setup", "--client", "dsh", "--dry-run"]);
expect(planned.exitCode).toBe(0);
expect(planned.json).toMatchObject({
status: "planned",
appliedActions: [],
plannedActions: expect.arrayContaining([
expect.objectContaining({ id: "configure_client:dsh", target: config }),
expect.objectContaining({ kind: "install_skill", target: skillRoot }),
]),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
const configured = await run(["setup", "--client", "dsh", "--yes"]);
expect(configured.exitCode).toBe(0);
expect(configured.json).toMatchObject({
status: "ready",
clients: { dsh: { status: "configured" } },
});
const text = await readFile(config, "utf8");
expect(text).toContain("# caller patch");
expect(text).toContain("rea-mcp");
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(skill, "utf8")).toContain(
"name: reverse-engineer-anything",
);
const doctor = await run(["doctor", "--client", "dsh", "--skill"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({ healthy: true });
const repeated = await run(["setup", "--client", "dsh", "--yes"]);
expect(repeated.exitCode).toBe(0);
expect(repeated.json).toMatchObject({
status: "ready",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(text);
const removed = await run(["uninstall"]);
expect(removed.exitCode).toBe(0);
expect(removed.json).toMatchObject({
status: "complete",
items: expect.arrayContaining([
expect.objectContaining({ name: "dsh", status: "removed" }),
]),
});
expect(parse(await readFile(config, "utf8"))).toEqual([
{ insert: [{ id: "caller", name: "caller-plugin" }] },
]);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
},
);
cliTest(
"DSH CLI previews, approves, repairs, launches MCP, repeats and uninstalls while preserving caller YAML",
async ({ cli }) => {