Compare commits

..
Author SHA1 Message Date
Cursor Agent 5c137ce50e chore: merge main into codex/audit-desktop-build 2026-11-11 02:26:33 +00:00
2885347cde test(ghidra): remove the retired processor-context suite (#9915)
* test(ghidra): keep the bridge context contract out of an empty suite

Source tests collect src/ghidra/GhidraFunctionValues.test.ts directly.
The empty describe failed that file with "No test found in suite" even
though every shard passed. Assert the bridge bindings at file level.

* test(ghidra): retire superseded source-text context assertions

Co-authored-by: gensokyo-dev <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: N0zoM1z0 <[email protected]>
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-10 21:20:07 -05:00
N0zoM1z0andgensokyo-dev a6a2527ade fix(artifacts): revalidate cached MFT observations
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev f8fc572e4a fix(ntfs): report contradictory declared record identities
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev ab9e5fa204 fix(ntfs): require space for the first attribute marker
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 8d45cb45c4 fix(ntfs): validate first attribute bounds in FILE records
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 7712e3185e fix(ntfs): retain incomplete coverage alongside fixup mismatches
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 466149169e fix(ntfs): validate aligned FILE record extents
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 1c2626edbd fix(ntfs): reject reserved update sequence values
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev b16d18f198 test(artifacts): cover independently cancelled MFT traversals
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 14030e2f11 fix(ntfs): expose unrecognized FILE record flag bits
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 9505c73824 fix(artifacts): retain only the bounded MFT header sample
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 1a446cdade fix(ntfs): label the system flag independently of extensions
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 1ef7f02cae test(ntfs): group MFT header and fixup regressions
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 7b86474be7 test(artifacts): use the MFT traversal iterable contract
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 5d10337709 feat(artifacts): expose a bounded sample of MFT record headers
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 8eadb872f2 fix(ntfs): preserve full-width MFT log sequence numbers
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev f170175ec8 fix(artifacts): retry interrupted MFT preparation
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev fbe09f84df fix(artifacts): verify MFT source before publishing metadata
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev ebb480ba22 fix(ntfs): buffer the admitted MFT byte range once
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev da1f029c2f fix(artifacts): admit MFT captures through CLI and MCP
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 4db9c166ef fix(ntfs): report contradictory FILE record extents
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 29fd6a7d03 fix(ntfs): accept older FILE record headers
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev d7338876d6 fix(ntfs): reject malformed MFT update sequence arrays
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 9df3f7174f fix(ntfs): keep record identity across invalid MFT slots
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
N0zoM1z0andgensokyo-dev 79e476204f fix(ntfs): preserve MFT reference sequence numbers
Co-authored-by: gensokyo-dev <[email protected]>
2026-11-11 10:03:35 +08:00
2SinceJuly 9c95218374 style(artifacts): apply the repository formatter to the MFT reader
The new NTFS $MFT files were committed unformatted, so the Static checks lane
failed on format:check. Formatting only; no behaviour change.

(cherry picked from commit dc6a6d40ff)
2026-11-11 10:03:35 +08:00
2SinceJuly d9d2641981 feat(artifacts): inventory NTFS $MFT record headers offline
An acquired $MFT stream had no reader, so an analyst holding one could only
treat it as an opaque file. Recognize the FILE signature of the first record
and inventory every record's header: sequence number, flags, used and total
bytes, base record reference and update-sequence array.

Each record's update-sequence fixups are verified against its sector
trailers. A mismatch keeps the header facts, is reported on the record and is
counted in the metadata, so a record that was not cleanly written is visible
rather than silently accepted. A missing or short array is reported as
unverified, a wrong signature stops the scan at its offset, and a trailing
partial record is reported as a byte count. Attributes, filenames and the
$UsnJrnl:$J journal are not decoded, so no path or change history is claimed.

Part of #9867

(cherry picked from commit ccb45f5712)
2026-11-11 10:03:35 +08:00
Cursor Agent c98594638d test(desktop): match reader source inspection diagnostics
Unreadable reader sources now report the source inspection failure, including the operating-system reason, instead of the old file wording.
2026-11-10 23:21:11 +00:00
morluto e2585aa7ce test(ghidra): qualify instruction mode with real provider 2026-11-10 17:58:04 -05:00
morluto 1d1c7f98ff test(ci): repair verifier fixtures and cleanup assertions 2026-11-10 17:58:04 -05:00
morluto b1f1b3eff3 fix(javascript): recognize inherited environment for NaN 2026-11-10 17:58:04 -05:00
morluto c1d0f2bb45 fix(environment): retain response cleanup through shutdown 2026-11-10 17:58:04 -05:00
morluto 04de5f3200 fix(artifacts): recover interrupted reader preparation 2026-11-10 17:58:04 -05:00
morluto 1bfc8e0dec fix(desktop)!: preserve build evidence and validate task inputs
BREAKING CHANGE: Witnessing requires the current generated verifier. Re-export bundles with older evaluators using the original capture Evidence and task inputs.
2026-11-10 17:33:06 -05:00
102 changed files with 4298 additions and 909 deletions

No files matched your search

+14 -3
View File
@@ -25,7 +25,7 @@ jobs:
node-version-file: .nvmrc
- name: Validate the SDK pin against the provider's verified release
run: node scripts/verify-ghidra-bridge-sources.mjs --check-sdk-pin >> "$GITHUB_ENV"
# The bridge probe imports only source-owned ARM/Thumb bytes and never
# The bridge probe imports only source-owned ARM, Thumb and MIPS bytes and never
# executes target code. All SDK/project state stays in runner storage.
- name: Acquire checksum-verified Ghidra SDK in isolated runner storage
shell: bash
@@ -46,7 +46,7 @@ jobs:
java_home_variable="JAVA_HOME_${GHIDRA_JAVA_MAJOR}_X64"
test -n "${!java_home_variable}"
JAVA_HOME="${!java_home_variable}" npm run verify:ghidra:bridge-sources -- --verified-sdk
- name: Inspect real ARM and Thumb instruction context through the bridge
- name: Inspect real ARM, Thumb and MIPS instruction context through the bridge
shell: bash
run: |
java_home_variable="JAVA_HOME_${GHIDRA_JAVA_MAJOR}_X64"
@@ -58,10 +58,21 @@ jobs:
-import "${probe_root}/arm-thumb.bin" -loader BinaryLoader -processor ARM:LE:32:v7 \
-noanalysis -readOnly -deleteProject \
-scriptPath "${GITHUB_WORKSPACE}/tests/conformance/ghidra;${GITHUB_WORKSPACE}/bridge/ghidra" \
-postScript ReaArmContextProbe.java "${GITHUB_WORKSPACE}/bridge/ghidra" \
-postScript ReaInstructionContextProbe.java "${GITHUB_WORKSPACE}/bridge/ghidra" \
> "${probe_root}/output.log" 2>&1 || { cat "${probe_root}/output.log"; exit 1; }
cat "${probe_root}/output.log"
grep -F 'REA_ARM_CONTEXT_OK arm=0 thumb=1 unavailable=null (injected provider value)' "${probe_root}/output.log"
mkdir -p "${probe_root}/mips-project"
# MIPS32 addiu v0,a0,3; MIPS16 li v0,90. These bytes are never executed.
printf '\003\000\202\044\132\152\000\000' > "${probe_root}/mips.bin"
timeout 180s "${GHIDRA_INSTALL_DIR}/support/analyzeHeadless" "${probe_root}/mips-project" MipsContext \
-import "${probe_root}/mips.bin" -loader BinaryLoader -processor MIPS:LE:32:default \
-noanalysis -readOnly -deleteProject \
-scriptPath "${GITHUB_WORKSPACE}/tests/conformance/ghidra;${GITHUB_WORKSPACE}/bridge/ghidra" \
-postScript ReaInstructionContextProbe.java "${GITHUB_WORKSPACE}/bridge/ghidra" mips \
> "${probe_root}/mips-output.log" 2>&1 || { cat "${probe_root}/mips-output.log"; exit 1; }
cat "${probe_root}/mips-output.log"
grep -F 'REA_MIPS_CONTEXT_OK standard=0 mips16=1' "${probe_root}/mips-output.log"
# Each probe imports source-owned bytes at 0x1000, away from the Cortex-M
# vector symbols that ARMCortex.pspec defines at 0, and decodes them from
# the language's default context, so M-profile Thumb state must hold at
+5
View File
@@ -262,6 +262,11 @@ in the bundle differs from what the export writes for it. A reset
relaunches the app, and REA waits until the computer is ready again before
answering, sending progress notifications while it waits.
Re-export bundles whose generated verifier uses an older evaluator before
witnessing them with current REA. The verifier must match the current export
exactly; re-exporting uses the existing capture Evidence and task inputs,
which remain unchanged.
Only a check that fails on what the app's view shows counts as a failure. A
check that fails because its file or table could not be read, such as an
SQLite file locked past the reader's wait, or because what it looks for may
+1
View File
@@ -26,6 +26,7 @@ for new work, roadmap granularity and producer-owned contracts.
- [Native call source coordinates](native/call-source-locations/spec.md) ([plan](native/call-source-locations/plan.md), [tasks](native/call-source-locations/tasks.md), [verification](native/call-source-locations/verification.md))
- [Go static string-header literal recovery](native/go-string-literals/spec.md) ([plan](native/go-string-literals/plan.md), [tasks](native/go-string-literals/tasks.md))
- [Windows Shell Link shortcut inspection](native/windows-shortcut/spec.md) ([plan](native/windows-shortcut/plan.md), [tasks](native/windows-shortcut/tasks.md))
- [NTFS $MFT and USN Journal inspection](native/ntfs-mft/spec.md) ([plan](native/ntfs-mft/plan.md), [tasks](native/ntfs-mft/tasks.md))
- [Solidity terminal metadata inspection](solidity/cbor-metadata/spec.md) ([plan](solidity/cbor-metadata/plan.md), [tasks](solidity/cbor-metadata/tasks.md), [verification](solidity/cbor-metadata/verification.md))
- [Inspect a V8 code cache container](v8/code-cache-inspection/spec.md) ([plan](v8/code-cache-inspection/plan.md), [tasks](v8/code-cache-inspection/tasks.md))
- [Deno compile executable inventory and extraction](artifacts/deno-standalone/spec.md) ([plan](artifacts/deno-standalone/plan.md), [tasks](artifacts/deno-standalone/tasks.md))
+39
View File
@@ -0,0 +1,39 @@
# Implementation plan
## Boundary and contract
Follow the existing artifact readers. `src/domain/windows/ntfsMft.ts` owns FILE
record bytes and coverage; `src/domain/artifactFormatMetadata.ts` owns the
`ntfs-mft` result schema. `NtfsMftArtifactReader` reads the admitted file
through `ArtifactFileSource` and exposes its facts through `formatMetadata()`.
A record stream is its own content, so the root occurrence carries every fact
and no members are enumerated.
Recognition lives in `hasMftFileRecordSignature` and is applied in
`classifyArtifactBytes`, next to the other unambiguous magic probes.
## Incremental work and validation
1. Define the first-step contract, limits and observations; add parser fixtures.
2. Implement the FILE record header and update-sequence fixup parse with
explicit limitations.
3. Add the reader, format descriptor and byte classification.
4. Decode attribute records, then `$FILE_NAME` attributes so a record's parent
reference, names and timestamps become explicit; keep hard links separate.
5. Parse `$UsnJrnl:$J` records and correlate them to records by full file
reference, including sequence numbers, reporting unresolved references.
6. Document the workflow in a native Windows artifact guide.
## Effects and compatibility
The workflow reads one caller-selected local file. It adds no target execution,
injection, mutation, protection recovery, network access, volume mount or live
filesystem access, so no maintainer scope decision is required.
`inspect_artifact` routing for every existing format is unchanged, and the new
format id appears only for bytes whose first record carries the `FILE`
signature.
## References
- https://learn.microsoft.com/en-us/windows/win32/fileio/master-file-table
- https://github.com/libyal/libfsntfs/blob/main/documentation/New%20Technologies%20File%20System%20(NTFS).asciidoc
+51
View File
@@ -0,0 +1,51 @@
# NTFS $MFT and USN Journal inspection
This specification records an implementation increment and its original problem
statement. For current behavior and limitations, see the artifact inventory
guide.
## Problem and outcome
REA has no reader for acquired NTFS metadata artifacts. An analyst holding a
captured `$MFT` stream cannot ask which FILE records it contains, whether their
update-sequence fixups survived acquisition, or which records are directories,
extensions of another record, or no longer in use. Add offline, read-only
inventory of a selected `$MFT` file, delivered in steps so each one merges on
its own.
## Requirements
- Recognize a `$MFT` stream by a plausible first `FILE` record header under
any file name. CLI and MCP target admission route it to the artifact reader.
- Validate each FILE record header: the `FILE` signature, sequence number, flags,
used and total byte counts, base record reference, and the update-sequence
array's offset, count and array bounds.
- Verify the update-sequence fixups: every sector trailer the array covers must
hold the array's sequence number. A mismatch keeps the record's header facts
and is reported per record and in the metadata count.
- Report a missing, misplaced or short update-sequence array as unverified
rather than as a clean record, and a trailing partial record as a byte count.
- Report the first invalid record signature and the number of invalid slots.
Continue at the next slot when the stream declared a supported record size.
With a fallback record size, stop at the first invalid signature.
- Bound the whole file at a fixed 512 MiB ceiling and report the ceiling as a
`limit` failure with its boundary.
- Return the first 32 decoded record headers with their source offsets and the
number of omitted headers. Aggregate counts cover the full parsed stream.
- Parse only the records' headers and fixups. Attributes, filenames, data
streams and the `$UsnJrnl:$J` journal are not decoded in this step, so no path,
file size, file reference correlation or change history is claimed.
## Acceptance
Synthesized fixtures cover a clean record, a failed fixup, a missing update
sequence array, an array shorter than the record's sector count, extension and
directory records, a record whose signature is wrong mid-stream, a trailing
partial record, an undeclared record size, a 4 KiB record, a stream shorter than
one header, bytes without the `FILE` signature, and the file-size ceiling.
Inventory tests cover the root occurrence's metadata and the coverage status
when a fixup fails, and classification tests cover several file names for the
same bytes.
Not covered in this step: real `$MFT` files written by a Windows host, USN
journal records, attribute decoding, and any correlation between the two.
+11
View File
@@ -0,0 +1,11 @@
# Tasks
- [x] Define the first-step scope, contract and limits.
- [x] Parse FILE record headers and update-sequence fixups with synthesized
fixtures and explicit limitations.
- [x] Add the reader, format descriptor and byte classification.
- [ ] Decode attribute records, then `$FILE_NAME` attributes with parent
references, names, hard links and timestamps.
- [ ] Parse `$UsnJrnl:$J` records and correlate them to records by full file
reference.
- [ ] Verify against real `$MFT` and journal captures from a Windows host.
+1 -1
View File
@@ -636,7 +636,7 @@ const PATH_SCOPES = {
"src/ghidra/GhidraJavaProperties.ts",
"src/ghidra/GhidraReleasePolicy.ts",
"scripts/verify-ghidra-bridge-sources.mjs",
"tests/conformance/ghidra/ReaArmContextProbe.java",
"tests/conformance/ghidra/ReaInstructionContextProbe.java",
"tests/conformance/ghidra/ReaComputedCallCoverageProbe.java",
"tests/conformance/ghidra/ReaDecodeProbe.java",
".github/workflows/ghidra-bridge-sources.yml",
+14 -13
View File
@@ -50,7 +50,7 @@ transport.stderr?.on("data", (bytes) => {
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const measurements = [];
const contract = toolContract("inspect_web_network_capture");
await withVerifierCleanup(async () => {
const report = await withVerifierCleanup(async () => {
try {
await client.connect(transport);
} catch (cause) {
@@ -196,7 +196,7 @@ await withVerifierCleanup(async () => {
});
}
await client.ping();
const report = {
return {
status: "passed",
profile: "aioquic-1.5.0-json-0.3",
measurements,
@@ -206,17 +206,6 @@ await withVerifierCleanup(async () => {
"No PCAP or keylog is read by this verifier; repeated STREAM coverage is not proof of retransmission or network loss.",
],
};
await writeFile(reportPath, JSON.stringify(report, null, 2) + "\n", {
flag: "wx",
mode: 0o600,
});
console.log(
JSON.stringify({
status: report.status,
cases: measurements.length,
report: reportPath,
}),
);
}, [
async () => {
await closeVerifierResources([
@@ -225,3 +214,15 @@ await withVerifierCleanup(async () => {
]);
},
]);
await writeFile(reportPath, JSON.stringify(report, null, 2) + "\n", {
flag: "wx",
mode: 0o600,
});
console.log(
JSON.stringify({
status: report.status,
cases: measurements.length,
report: reportPath,
}),
);
+3
View File
@@ -97,6 +97,7 @@ import {
isDfuSeFile,
} from "../domain/firmware/dfuse.js";
import { hasFitImagesNode } from "../domain/firmware/fitImage.js";
import { hasMftFileRecordHeader } from "../domain/windows/ntfsMft.js";
import {
locateEspFlashLayout,
type EspFlashSelection,
@@ -816,6 +817,7 @@ const detectArtifactFormat = async (
});
if (esp === "esp-image") return "esp-image";
if (hasFitImagesNode(magic)) return "fit";
if (hasMftFileRecordHeader(magic)) return "ntfs-mft";
// Binary plists, including keyed archives, often use other extensions.
if (hasBinaryPlistSignature(magic)) return "plist";
const named = namedArtifactFormat(lower);
@@ -899,6 +901,7 @@ const isArchiveFormat = (
"dfuse",
"esp-flash-image",
"fit",
"ntfs-mft",
].includes(format);
/** Whether the leading bytes begin any executable header family, valid or not. */
@@ -3,10 +3,7 @@ import { createHash } from "node:crypto";
import { expect, it } from "vitest";
import { parseReferenceSourceEntries } from "./ReferenceSourceImportEntries.js";
import {
historicalSourceInventoryHasPartialFacts,
historicalSourceLanguages,
} from "../domain/referenceSourceGraph.js";
import { historicalSourceLanguages } from "../domain/referenceSourceGraph.js";
import type { ReferenceSourceRead } from "../reference/ReferenceSourceReaderTypes.js";
it("projects an unsupported non-regular entry as unknown kind instead of file", () => {
@@ -101,100 +98,6 @@ it("keeps source entries when a module has an empty specifier", () => {
expect(parsed.limitations[0]).toMatch(/not recorded.*relationship/iu);
});
it("resolves immediately invoked loaders from their proven source bases", () => {
const files = [
[
"main.cjs",
'(() => require)()("./dep.cjs"); (() => () => {})()("./local.cjs");',
],
[
"main.mjs",
[
'import {createRequire} from "node:module";',
'createRequire(new URL("./sub/base.cjs", import.meta.url))("./dep.cjs");',
'createRequire(new URL("./sub/base.cjs", import.meta.url)).call(null, "./member.cjs");',
].join("\n"),
],
["dep.cjs", ""],
["sub/dep.cjs", ""],
["member.cjs", ""],
["sub/member.cjs", ""],
] as const;
const parsed = parseReferenceSourceEntries(
{
root: "/selected/source",
entries: files.map(([path, content]) => ({
status: "read",
kind: "file",
path,
bytes: Buffer.from(content),
size: Buffer.byteLength(content),
})),
bytesRead: files.reduce(
(sum, [, content]) => sum + Buffer.byteLength(content),
0,
),
limitations: [],
},
[],
);
expect(
parsed.relationships.filter(({ kind }) => kind === "requires"),
).toEqual([
{
from_path: "main.cjs",
to: "dep.cjs",
kind: "requires",
resolution: "internal",
parse_state: "parsed",
},
{
from_path: "main.mjs",
to: "sub/dep.cjs",
kind: "requires",
resolution: "internal",
parse_state: "parsed",
},
]);
});
it.each([
["function load(name) { require(name); }", true],
["function load(require, name) { require(name); }", false],
["require(7); require();", false],
] as const)(
"reports unresolved CommonJS target coverage for %s",
(source, partial) => {
const bytes = Buffer.from(source);
const parsed = parseReferenceSourceEntries(
{
root: "/selected/source",
entries: [
{
status: "read",
kind: "file",
path: "main.cjs",
bytes,
size: bytes.length,
},
],
bytesRead: bytes.length,
limitations: [],
},
[],
);
expect(parsed.relationships).toEqual([]);
expect(
historicalSourceInventoryHasPartialFacts({
...parsed,
parse_failures: parsed.parseFailures,
exclusions: [],
}),
).toBe(partial);
expect(parsed.entries[0]?.limitations).toEqual(parsed.limitations);
},
);
it("retains Kotlin source identity and language across the inventory projection", () => {
const files = [
[
@@ -135,6 +135,7 @@ const TARGETS: TargetFixtures = {
espFlash: { selected: true, flashOffset: null, partitionTableOffset: null },
},
fit: { ...archive, format: "fit" },
"ntfs-mft": { ...archive, format: "ntfs-mft" },
plist: { ...artifact, format: "plist" },
javascript: { ...artifact, format: "javascript" },
"source-map": { ...artifact, format: "source-map" },
@@ -0,0 +1,38 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { seededLockFiles } from "./DesktopBuildBundle.js";
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"keeps lock inspection failures separate from empty and partially examined seeds",
async () => {
const root = await createTestTempDirectory("rea-seeded-locks-");
expect(await seededLockFiles(root)).toEqual({ locks: [], unreadable: [] });
const envs = join(root, "envs");
const denied = join(envs, "denied", "seed");
const available = join(envs, "available", "seed");
await mkdir(denied, { recursive: true });
await mkdir(available, { recursive: true });
await writeFile(join(available, "SingletonLock"), "controlled lock");
await chmod(denied, 0);
try {
const found = await seededLockFiles(root);
expect(found.locks).toEqual(["envs/available/seed/SingletonLock"]);
expect(found.unreadable).toEqual([
{ path: denied, reason: expect.stringContaining("EACCES") },
]);
} finally {
await chmod(denied, 0o700);
}
await chmod(envs, 0);
try {
expect(await seededLockFiles(root)).toEqual({
locks: [],
unreadable: [{ path: envs, reason: expect.stringContaining("EACCES") }],
});
} finally {
await chmod(envs, 0o700);
}
},
);
+44 -6
View File
@@ -20,6 +20,9 @@ import {
import { isLockFile } from "../../domain/desktop/appExportUnowned.js";
import { AGENTENV_PROVIDER } from "../../desktop/AgentEnvComputerHelper.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { bindArtifactFileCleanup } from "../../artifacts/ArtifactFileOperation.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
const START = "start_build_computer";
const MAX_KEY_BYTES = 1024 * 1024;
@@ -76,6 +79,7 @@ const readAptKey = async (path: string): Promise<Buffer> => {
const writeBuildBundle = async (
request: BuildRequest,
payload: ReaPayload,
resources: ArtifactResourceScope,
): Promise<{
readonly workspace: PrivateRuntimeRoot;
readonly bundle: string;
@@ -103,7 +107,23 @@ const writeBuildBundle = async (
}
return { workspace, bundle, name };
} catch (cause: unknown) {
await workspace.close();
const released = await resources.release({
kind: "private-runtime-root",
resource: workspace.path,
root: workspace,
});
if (released.kind === "failed") {
const cleanup = resources.cleanupFailure({ kind: "failed", cause }, [
released,
]);
const error = new ProviderAdapterError(AGENTENV_PROVIDER, START, {
cause,
userMessage: cause instanceof Error ? cause.message : String(cause),
cleanup: cleanup.cleanup,
});
bindArtifactFileCleanup(cleanup, error);
throw error;
}
throw cause;
}
};
@@ -115,7 +135,8 @@ const writeBuildBundle = async (
export const writeRequestBundle = async (
request: BuildRequest,
environment: Readonly<NodeJS.ProcessEnv>,
) => writeBuildBundle(request, await reaPayload(environment));
resources: ArtifactResourceScope,
) => writeBuildBundle(request, await reaPayload(environment), resources);
/**
* The lock files in a bundle folder's seeds, as `envs/<name>/seed/<home
@@ -125,16 +146,33 @@ export const writeRequestBundle = async (
*/
export const seededLockFiles = async (
bundle: string,
): Promise<readonly string[]> => {
): Promise<{
readonly locks: readonly string[];
readonly unreadable: readonly {
readonly path: string;
readonly reason: string;
}[];
}> => {
const environments = join(bundle, "envs");
const names = await readdir(environments).catch(() => []);
const unreadable: { path: string; reason: string }[] = [];
const unavailable = (path: string, cause: unknown) => {
if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT"))
unreadable.push({
path,
reason: cause instanceof Error ? cause.message : String(cause),
});
return [];
};
const names = await readdir(environments).catch((cause: unknown) =>
unavailable(environments, cause),
);
const locks: string[] = [];
for (const name of names) {
const seed = join(environments, name, "seed");
const entries = await readdir(seed, {
recursive: true,
withFileTypes: true,
}).catch(() => []);
}).catch((cause: unknown) => unavailable(seed, cause));
const homes = new Set(
entries
.filter((entry) => entry.isFile())
@@ -147,5 +185,5 @@ export const seededLockFiles = async (
for (const home of homes)
if (isLockFile(home, [], homes)) locks.push(`envs/${name}/seed/${home}`);
}
return locks.sort();
return { locks: locks.sort(), unreadable };
};
@@ -1,11 +1,157 @@
import { expect, it, vi } from "vitest";
import { AgentEnvComputer } from "../../desktop/AgentEnvComputer.js";
import { access, chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { request } from "../../domain/desktop/appBuild.fixture.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
AgentEnvComputer,
ComputerStartFailure,
} from "../../desktop/AgentEnvComputer.js";
import { ComputerHelper } from "../../desktop/AgentEnvComputerHelper.js";
import { ScreenJudgeProcess } from "../../desktop/ScreenJudgeProcess.js";
import { BuildComputerLongRuns } from "../../desktop/BuildComputerLongRuns.js";
import { DesktopBuildComputers } from "./DesktopBuildComputers.js";
import { DesktopRemoteTaskReaders } from "./DesktopRemoteTaskReaders.js";
it("resolves the original failed start's cleanup after its retained computer closes", async () => {
const release = vi
.fn()
.mockResolvedValueOnce({
verified: false,
reason: "container busy",
resources: ["sandbox"],
})
.mockResolvedValue({ verified: true, teardown: "agentenv" });
const spawn = vi.spyOn(ComputerHelper, "spawn").mockResolvedValue({
release,
output: () => undefined,
} as never);
const connect = vi
.spyOn(AgentEnvComputer, "connect")
.mockRejectedValue(new Error("readiness failed"));
const computers = new DesktopBuildComputers({
REA_AGENT_ENV_COMMAND: "/runner",
REA_DOCKER_COMMAND: "/docker",
});
try {
const started = await computers.start(
{ source: { kind: "bundle", path: "/bundle" } },
new AbortController().signal,
);
if (started.ok) throw new Error("Expected failed start");
const id = started.error.diagnostics?.computer_id;
if (typeof id !== "string")
throw new Error("Expected retained computer id");
expect(started.error.cleanupIncomplete).toBe(true);
expect(started.error.cleanupResources).toEqual(["sandbox"]);
expect((await computers.close(id)).ok).toBe(true);
expect(started.error.cleanupIncomplete).toBe(false);
expect(started.error.cleanupResources).toEqual([]);
expect(started.error.userMessage).toBe("readiness failed");
} finally {
await computers.closeAll();
spawn.mockRestore();
connect.mockRestore();
}
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"preserves a readiness failure while reporting that seed locks could not be checked",
async () => {
const bundle = await createTestTempDirectory("rea-unreadable-build-seed-");
const envs = join(bundle, "envs");
await mkdir(envs);
await chmod(envs, 0);
const original = new ComputerStartFailure(
"Application readiness failed",
"Repair the app",
{ reason: "not_ready" },
);
const spawn = vi.spyOn(ComputerHelper, "spawn").mockResolvedValue({
release: async () => ({ verified: true, teardown: "agentenv" }),
output: () => undefined,
} as never);
const connect = vi
.spyOn(AgentEnvComputer, "connect")
.mockRejectedValue(original);
const computers = new DesktopBuildComputers({
REA_AGENT_ENV_COMMAND: "/runner",
REA_DOCKER_COMMAND: "/docker",
});
try {
const started = await computers.start(
{ source: { kind: "bundle", path: bundle } },
new AbortController().signal,
);
expect(started.ok).toBe(false);
if (started.ok) throw new Error("Expected readiness failure");
expect(started.error.userMessage).toContain(original.message);
expect(started.error.userMessage).toContain("could not check");
expect(started.error.cause).toMatchObject({
reason: "not_ready",
cause: original,
});
} finally {
await chmod(envs, 0o700);
await computers.closeAll();
spawn.mockRestore();
connect.mockRestore();
}
},
);
it("retains a failed bundle workspace and its write error until shutdown retries cleanup", async () => {
const folder = await createTestTempDirectory("rea-build-bundle-cleanup-");
const payload = join(folder, "payload.tar");
await writeFile(payload, "controlled payload");
const create = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot);
let workspace: PrivateRuntimeRoot | undefined;
const created = vi
.spyOn(PrivateRuntimeRoot, "create")
.mockImplementation(async (options) => {
workspace = await create(options);
await writeFile(join(workspace.path, "bundle"), "blocks bundle creation");
vi.spyOn(workspace, "close").mockRejectedValueOnce(
new Error("workspace removal failed"),
);
return workspace;
});
const computers = new DesktopBuildComputers({
REA_AGENT_ENV_COMMAND: "/runner",
REA_DOCKER_COMMAND: "/docker",
REA_BUILD_COMPUTER_REA_ARCHIVE: payload,
});
try {
const started = await computers.start(
{
source: request({
kind: "archive",
package: "mousepad",
extra_packages: [],
}),
},
new AbortController().signal,
);
expect(started.ok).toBe(false);
if (started.ok || workspace === undefined)
throw new Error("Expected bundle creation failure");
expect(started.error.userMessage).toContain("ENOTDIR");
expect(started.error.cleanup?.reason).toContain("workspace removal failed");
expect(started.error.cleanupResources).toEqual([workspace.path]);
await expect(access(workspace.path)).resolves.toBeUndefined();
await computers.closeAll();
await expect(access(workspace.path)).rejects.toMatchObject({
code: "ENOENT",
});
expect(started.error.cleanupIncomplete).toBe(false);
} finally {
created.mockRestore();
await computers.closeAll().catch(() => computers.closeAll());
await workspace?.close();
}
});
it.each([false, true])(
"releases the computer even if judge cleanup fails (computer also fails: %s)",
async (computerFails) => {
@@ -106,11 +106,23 @@ interface HeldComputer {
readonly turns: DesktopBuildTurns;
readonly cleanup: {
resources: readonly string[];
errors: Set<WeakRef<ProviderCleanupError>>;
errors: Set<WeakRef<AnalysisError>>;
};
closing: boolean;
}
/** Bind every returned teardown failure to the computer retained for retry. */
const bindCleanupFailure = (held: HeldComputer, error: AnalysisError): void => {
error.bindCleanupResourceOwner({
get cleanupResources() {
return held.cleanup.resources;
},
});
for (const reference of held.cleanup.errors)
if (reference.deref() === undefined) held.cleanup.errors.delete(reference);
held.cleanup.errors.add(new WeakRef(error));
};
/** What the build step tools work on: a live computer, its capture, its witness and the turns they take. */
export interface BuildComputerSteps {
readonly computer: AgentEnvComputer;
@@ -325,13 +337,21 @@ const withSeededLocks = async (
): Promise<unknown> => {
if (source.kind !== "bundle" || !computerFailedOnReadiness(cause))
return cause;
const locks = await seededLockFiles(source.path);
return locks.length === 0
const { locks, unreadable } = await seededLockFiles(source.path);
const notices = [
...(locks.length === 0 ? [] : [seededLockStartNotice(locks)]),
...(unreadable.length === 0
? []
: [
`REA could not check these seed folders for lock files: ${unreadable.map(({ path, reason }) => `${path}: ${reason}`).join("; ")}. Other lock files remain unknown.`,
]),
];
return notices.length === 0
? cause
: new ComputerStartFailure(
`${cause.message} ${seededLockStartNotice(locks)}`,
`${cause.message} ${notices.join(" ")}`,
cause.remediation,
{ cause: cause.cause, reason: cause.reason },
{ cause, reason: cause.reason },
);
};
@@ -466,7 +486,7 @@ export class DesktopBuildComputers {
target =
source.kind === "bundle"
? { bundle: source.path, name: source.path }
: await writeRequestBundle(source, environment);
: await writeRequestBundle(source, environment, this.#work.resources);
} catch (cause: unknown) {
return err(failure(START, cause, signal));
}
@@ -545,9 +565,16 @@ export class DesktopBuildComputers {
const failed = signal.aborted
? cause
: await withSeededLocks(source, cause);
return err(
startFailure(failed, signal, owner?.output(), { id, release }),
);
const error = startFailure(failed, signal, owner?.output(), {
id,
release,
});
const retained = this.#computers.get(id);
if (!release.verified && retained !== undefined) {
retained.cleanup.resources = release.resources;
bindCleanupFailure(retained, error);
}
return err(error);
}
}
@@ -699,15 +726,7 @@ export class DesktopBuildComputers {
{ reason: release.reason },
{ operation: CLOSE, remediationAction: release.reason },
);
failure.bindCleanupResourceOwner({
get cleanupResources() {
return held.cleanup.resources;
},
});
for (const reference of held.cleanup.errors)
if (reference.deref() === undefined)
held.cleanup.errors.delete(reference);
held.cleanup.errors.add(new WeakRef(failure));
bindCleanupFailure(held, failure);
return err(failure);
}
@@ -1,3 +1,7 @@
import * as buildEnvironment from "../../desktop/BuildComputerEnvironment.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { renderSmokeTask } from "../../domain/desktop/appExport.js";
import { MEASURE_BUILD_TASK_CONTRACT } from "../../contracts/desktopBuildMeasureContract.js";
import {
guestFileAnswerCeiling,
guestFileAnswerWorkingBytes,
@@ -18,7 +22,11 @@ import {
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import type { SolveReport } from "../../desktop/AgentEnvSolveHelper.js";
import { measureBuildTask, type Solver } from "./DesktopBuildSolves.js";
import {
measureBuildTask,
measureInFreshComputers,
type Solver,
} from "./DesktopBuildSolves.js";
/** A bundle holding stand-in steps and verifiers for these tasks, and a README. */
const bundleWith = async (...tasks: string[]) => {
@@ -422,3 +430,124 @@ it("retains completed solves when the destination becomes unreadable before publ
"invalid",
);
});
it.each(["../../outside", "nested/task", "nested\\task", ".", ".."])(
"refuses invalid selected task names before any file read or solve: %s",
async (task) => {
const read = vi
.spyOn(hostFiles, "readHostFile")
.mockRejectedValue(new Error("invalid task must not reach filesystem"));
const solve = vi.fn<Solver>();
try {
const result = await measureBuildTask(
request("/unused-bundle", task),
solve,
new AbortController().signal,
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError", issues: [{ path: ["task"] }] },
});
expect(read).not.toHaveBeenCalled();
expect(solve).not.toHaveBeenCalled();
} finally {
read.mockRestore();
}
},
);
it("keeps the portable smoke name selectable independently of authoring reservations", async () => {
const bundle = await bundleWith("smoke");
const { solver, calls } = counting();
const result = await measureBuildTask(
request(bundle, "smoke"),
solver,
new AbortController().signal,
);
expect(result.ok).toBe(true);
expect(calls).toEqual(["smoke", "smoke", "smoke"]);
});
it("refuses invalid measurement identity before resolving the fresh-computer environment", async () => {
const environment = vi
.spyOn(buildEnvironment, "resolveBuildComputerEnvironment")
.mockRejectedValue(
new Error("invalid task must not resolve an environment"),
);
const read = vi.spyOn(hostFiles, "readHostFile");
const resources = new ArtifactResourceScope();
try {
const result = await measureInFreshComputers(
request("/unused-bundle", "../../outside"),
{
environment: {},
defaults: {},
retainCleanup: () => undefined,
resources,
},
new AbortController().signal,
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError", issues: [{ path: ["task"] }] },
});
expect(environment).not.toHaveBeenCalled();
expect(read).not.toHaveBeenCalled();
} finally {
environment.mockRestore();
read.mockRestore();
await resources.close();
}
});
it("advertises the same portable lookup names without changing their spelling", () => {
for (const task of ["add-eggs", "123-task", "a".repeat(63), "smoke"])
expect(
MEASURE_BUILD_TASK_CONTRACT.inputSchema.parse(
request("/unused-bundle", task),
).task,
).toBe(task);
for (const task of [
"../../outside",
"nested/task",
"nested\\task",
".",
"..",
"con",
"123",
"a".repeat(64),
])
expect(
MEASURE_BUILD_TASK_CONTRACT.inputSchema.safeParse(
request("/unused-bundle", task),
).success,
).toBe(false);
});
it("keeps a generated deploy-only smoke task inapplicable without its measurement verifier", async () => {
const bundle = await createTestTempDirectory("measured-smoke-");
await mkdir(join(bundle, "tasks"));
await mkdir(join(bundle, "artifacts", "check_app"), { recursive: true });
await writeFile(
join(bundle, "tasks", "smoke.json"),
renderSmokeTask({ name: "app" }),
);
await writeFile(
join(bundle, "artifacts", "check_app", "verify.py"),
"# generated deployment check\n",
);
const solve = vi.fn<Solver>();
const result = await measureBuildTask(
request(bundle, "smoke"),
solve,
new AbortController().signal,
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
userMessage: expect.stringContaining("artifacts/smoke-check/verify.py"),
},
});
expect(solve).not.toHaveBeenCalled();
});
+37 -10
View File
@@ -1,3 +1,7 @@
import {
parsePortableBundleName,
PORTABLE_BUNDLE_NAME_CONSTRAINT,
} from "../../domain/portableBundleName.js";
import { createHash } from "node:crypto";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
@@ -89,6 +93,24 @@ const refused = (userMessage: string, remediationAction: string) =>
conformsToInputContract: true,
});
/** Refuse malformed lookup identity before reading files or resolving a solver. */
const admitTaskName = (name: string): Result<string, AnalysisError> => {
const parsed = parsePortableBundleName(name);
if (parsed.ok) return parsed;
const message = `Task ${JSON.stringify(name)} must be ${PORTABLE_BUNDLE_NAME_CONSTRAINT}.`;
return err(
new AnalysisInputError(
MEASURE,
{
userMessage: message,
remediationAction:
"Select the exact portable task name written under the bundle's tasks directory.",
},
[{ path: ["task"], reason: "invalid_value", message }],
),
);
};
/** The records a difficulty file holds, each read only as far as the README names it. */
const recordsSchema = z.looseObject({
tasks: z.record(
@@ -271,13 +293,16 @@ export const measureBuildTask = async (
progress: ProgressReporter = silentProgressReporter,
resources: ArtifactResourceScope = new ArtifactResourceScope(),
): Promise<Result<MeasuredTask, AnalysisError>> => {
const taskName = admitTaskName(request.task);
if (!taskName.ok) return taskName;
const task = taskName.value;
const solves: SolveRecord[] = [];
const retainSolves = (failure: AnalysisError): AnalysisError => {
if (solves.length > 0)
failure.retainPartialObservation({
kind: "partial-task-measurement",
bundle: request.bundle,
task: request.task,
task: task,
solves: [...solves],
});
return failure;
@@ -285,7 +310,7 @@ export const measureBuildTask = async (
let agentenv: string | null = null;
let stopped: StopReason = "decided";
try {
const digest = await taskDigest(request.bundle, request.task, signal);
const digest = await taskDigest(request.bundle, task, signal);
if (!digest.ok) return digest;
// Refuse records REA could not keep before any solve is paid for.
const records = await readRecords(request.bundle, signal);
@@ -301,15 +326,15 @@ export const measureBuildTask = async (
phase: MEASURE,
completed: solves.length,
total: null,
message: `solve ${String(solves.length + 1)} of ${request.task} with ${request.model}`,
message: `solve ${String(solves.length + 1)} of ${task} with ${request.model}`,
})
.catch(() => undefined);
const report = await solver(request, signal);
const report = await solver({ ...request, task }, signal);
if (!("outcome" in report))
return err(
retainSolves(
refused(
`A solve of ${request.task} did not run: ${report.error}`,
`A solve of ${task} did not run: ${report.error}`,
"Fix what the error names, such as the model endpoint agentenv needs (LITELLM_BASE_URL and LITELLM_API_KEY where REA starts, or [model] in .agentenv/config.toml), and measure again.",
),
),
@@ -329,7 +354,7 @@ export const measureBuildTask = async (
});
const file = await recordMeasure(
request.bundle,
request.task,
task,
record,
signal,
resources,
@@ -338,7 +363,7 @@ export const measureBuildTask = async (
const { versions: _versions, ...reported } = record;
return ok({
bundle: request.bundle,
task: request.task,
task: task,
...reported,
difficulty_file: file.value,
});
@@ -374,7 +399,7 @@ export const measureBuildTask = async (
cleanup,
})
: new ProviderAdapterError(AGENTENV_PROVIDER, MEASURE, {
userMessage: `Measuring ${request.task} could not close an input file.`,
userMessage: `Measuring ${task} could not close an input file.`,
cause,
cleanup,
});
@@ -387,7 +412,7 @@ export const measureBuildTask = async (
: signal.aborted
? new AnalysisCancelledError(MEASURE, { cause: signal.reason })
: new ProviderAdapterError(AGENTENV_PROVIDER, MEASURE, {
userMessage: `Measuring ${request.task} failed after ${String(solves.length)} solve(s): ${errorText(cause)}`,
userMessage: `Measuring ${task} failed after ${String(solves.length)} solve(s): ${errorText(cause)}`,
remediationAction:
"Check the bundle files and host I/O error, then retry or retain the completed solve results.",
cause,
@@ -408,13 +433,15 @@ export const measureInFreshComputers = async (
signal: AbortSignal,
progress?: ProgressReporter,
): Promise<Result<MeasuredTask, AnalysisError>> => {
const taskName = admitTaskName(request.task);
if (!taskName.ok) return taskName;
const environment = await resolveBuildComputerEnvironment(
host.environment,
process.platform,
host.defaults,
);
return measureBuildTask(
request,
{ ...request, task: taskName.value },
(solve, turn) =>
runSolveHelper({
...solve,
@@ -1,4 +1,4 @@
import { mkdir, stat, writeFile } from "node:fs/promises";
import { access, mkdir, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -14,7 +14,6 @@ import {
renderTaskVerifier,
taskVerifierArtifact,
} from "../../domain/desktop/appTaskPython.js";
import { isPortableBundleName } from "../environment/environmentBundle.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { BuildComputerActionLog } from "./DesktopBuildActionLog.js";
import {
@@ -52,6 +51,77 @@ const witnessAt = async (bundle: string) =>
);
describe("bundle task reads", () => {
it("keeps the selected record directory through failed-save retries", async () => {
const directory = await createTestTempDirectory("witness-original-");
const other = await createTestTempDirectory("witness-other-");
let endAttempts = 0;
const witness = new DesktopBuildWitness(
{
...computer,
appData: async () => [
{
kind: "data",
data: {
state: {
"Documents/today.txt": {
format: "text",
view: { lines: ["eggs"], line_count: 1, truncated: false },
error: null,
},
},
},
},
],
startRecording: async () => ({
recording_id: "rec",
started_at: "2026-11-10T00:00:00.000Z",
}),
endRecording: async () => {
if (++endAttempts === 1) throw new Error("recording busy");
return { recording_id: "rec", segments: [] };
},
recordingSegments: async () => [],
},
new BuildComputerActionLog(),
{ ...SETTLE_TIMING, windowMs: 0 },
);
const signal = new AbortController().signal;
const first = await witness.check(
{ task, stage: "seed", directory },
signal,
);
expect(first.ok).toBe(false);
if (first.ok) throw new Error("Expected recording failure");
expect(first.error.userMessage).toContain("recording busy");
const refused = await witness.check(
{ task, stage: "seed", directory: other },
signal,
);
expect(refused.ok).toBe(false);
if (refused.ok) throw new Error("Expected directory refusal");
expect(refused.error.userMessage).toContain(directory);
expect(endAttempts).toBe(1);
await expect(access(join(directory, "witness.json"))).rejects.toThrow();
await expect(access(join(other, "witness.json"))).rejects.toThrow();
const saved = await witness.check(
{ task, stage: "seed", directory },
signal,
);
expect(saved.ok).toBe(true);
if (!saved.ok) throw saved.error;
expect(saved.value.witness?.record?.path).toBe(
join(directory, "witness.json"),
);
const savedAgain = await witness.check(
{ task, stage: "seed", directory: other },
signal,
);
expect(savedAgain.ok).toBe(false);
expect(endAttempts).toBe(2);
});
it("returns a cancelled result when reading the bundle's task is aborted", async () => {
const bundle = await createTestTempDirectory("witness-bundle-");
const directory = await createTestTempDirectory("witness-record-");
@@ -87,7 +157,7 @@ describe("bundle task reads", () => {
it("reads a task whose prompt is larger than the old 1 MiB file cap", async () => {
const prompt = `Add ${"eggs ".repeat(Math.ceil((1.1 * 1024 * 1024) / 5))}end`;
const given = { ...task, prompt };
const parsed = parseDesktopTask(given, isPortableBundleName);
const parsed = parseDesktopTask(given);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
const large = parsed.value;
+27 -11
View File
@@ -35,7 +35,6 @@ import type {
RecordingManifest,
} from "../../desktop/AgentEnvComputer.js";
import { AGENTENV_PROVIDER } from "../../desktop/AgentEnvComputerHelper.js";
import { isPortableBundleName } from "../environment/environmentBundle.js";
import {
silentProgressReporter,
type ProgressReporter,
@@ -104,6 +103,18 @@ const refused = (userMessage: string, remediationAction: string) =>
const taskDigest = (task: DesktopTask) =>
createHash("sha256").update(JSON.stringify(task)).digest("hex");
/** A retry cannot redirect an ended witness to another folder. */
const recordDirectoryRefusal = (
expected: string,
requested: string | undefined,
): AnalysisError | undefined =>
requested !== undefined && requested !== expected
? refused(
`This witness's record belongs to ${expected}, not ${requested}.`,
"Ask again without directory or with the original folder; another witness needs a fresh computer.",
)
: undefined;
/** Whether a folder can take the record: absent, or empty. */
const usableFolder = async (directory: string): Promise<boolean> =>
readdir(directory).then(
@@ -228,7 +239,7 @@ export class DesktopBuildWitness {
signal: AbortSignal,
progress: ProgressReporter = silentProgressReporter,
): Promise<Result<CheckedTask, AnalysisError>> {
const parsed = parseDesktopTask(input.task, isPortableBundleName);
const parsed = parseDesktopTask(input.task);
if (!parsed.ok)
return err(
refused(
@@ -238,8 +249,15 @@ export class DesktopBuildWitness {
);
const task = parsed.value;
const { stage } = input;
if (stage !== undefined && this.#witness?.state === "saving")
return this.#resave(this.#witness, task, stage, signal);
if (stage !== undefined && this.#witness?.state === "saving") {
const directoryRefusal = recordDirectoryRefusal(
this.#witness.directory,
input.directory,
);
return directoryRefusal === undefined
? this.#resave(this.#witness, task, stage, signal)
: err(directoryRefusal);
}
const saved =
stage === undefined
? undefined
@@ -439,13 +457,11 @@ export class DesktopBuildWitness {
)
return undefined;
// A folder the record was not saved to gets nothing written, so it is refused.
if (directory !== undefined && directory !== witness.directory)
return err(
refused(
`This witness's record was saved to ${witness.directory}, not ${directory}.`,
"Ask again without directory or with the folder it was saved to; another witness needs a fresh computer.",
),
);
const directoryRefusal = recordDirectoryRefusal(
witness.directory,
directory,
);
if (directoryRefusal !== undefined) return err(directoryRefusal);
return ok({
...counted(task, filed),
witness: summaryOf(filed, null, witness.record),
@@ -21,20 +21,17 @@ const manifest: RecordingManifest = {
};
const witness = async (): Promise<EndedWitness> => {
const parsed = parseDesktopTask(
{
name: "add-eggs",
prompt: "Add eggs.",
checks: [
{
kind: "lines_present",
file: "Documents/today.txt",
lines: ["eggs"],
},
],
},
(name) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name),
);
const parsed = parseDesktopTask({
name: "add-eggs",
prompt: "Add eggs.",
checks: [
{
kind: "lines_present",
file: "Documents/today.txt",
lines: ["eggs"],
},
],
});
if (!parsed.ok) throw new Error(parsed.error);
return {
task: parsed.value,
@@ -19,7 +19,7 @@ import {
withExtraPackages,
} from "../../domain/desktop/appExportInstall.js";
import type { DesktopApplicationCapture } from "../../domain/desktop/desktopCapture.js";
import { isPortableBundleName } from "../environment/environmentBundle.js";
import { isPortableBundleName } from "../../domain/portableBundleName.js";
const OPERATION = "export_desktop_application";
const MAX_DOWNLOAD_INSTALL_BYTES = 64 * 1024;
@@ -189,3 +189,37 @@ it("does not start a second cleanup while a timed-out cleanup may still be runni
expect(calls).toBe(1);
expect(owner.cleanupResources).toHaveLength(2);
});
it.each([
{ ...success, exit_code: 4, stderr: "reader failed" },
{ ...success, stdout: "invalid reader answer" },
])(
"preserves earlier views and absences when a later runner fails after settling (%#)",
async (failed) => {
let readers = 0;
const owner = new DesktopRemoteTaskReaders(async (argv) => {
if (argv[3] === PYTHON_READER_CLEANUP) return success;
readers += 1;
if (readers === 1) return success;
if (readers === 2)
return { ...success, stdout: JSON.stringify({ absent: true }) };
return failed;
});
const failure = await owner
.read(
[reader, { ...reader, id: "absent" }, { ...reader, id: "failed" }],
new AbortController().signal,
)
.catch((error: unknown) => error);
expect(failure).toMatchObject({
operation: "check_build_task",
diagnostics: {
completed_reader_views: {
note: { format: "json", view: { value: 7 } },
},
completed_reader_absent: ["absent"],
},
});
expect(owner.cleanupResources).toEqual([]);
},
);
@@ -14,6 +14,7 @@ import {
type ReaderLease,
} from "../../domain/desktop/appTaskReaders.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import {
AGENTENV_PROVIDER,
type ComputerRelease,
@@ -137,7 +138,12 @@ export class DesktopRemoteTaskReaders {
signal.aborted ? this.#cancelled(signal, views, absent) : undefined,
);
if (signal.aborted) throw this.#cancelled(signal, views, absent);
if (failure !== undefined) throw failure;
if (failure !== undefined)
throw new ProviderAdapterError(AGENTENV_PROVIDER, "check_build_task", {
cause: failure,
userMessage: `The task reader could not complete: ${failure instanceof Error ? failure.message : String(failure)}`,
diagnostics: this.#facts(views, absent),
});
}
return views;
}
+1 -5
View File
@@ -45,7 +45,6 @@ import { EvidenceFileError } from "../../domain/evidenceErrors.js";
import { err } from "../../domain/result.js";
import { describeValidationFailure } from "../../domain/validationFailure.js";
import { isWithinAny } from "../../domain/desktop/desktopStateDiff.js";
import { isPortableBundleName } from "../environment/environmentBundle.js";
import { readJsonFile } from "../JsonFiles.js";
import { desktopOperationFailure } from "./DesktopCaptureRefusals.js";
import { refuse } from "./DesktopExportInstall.js";
@@ -663,10 +662,7 @@ export const admitDesktopTasks = async (
): Promise<AdmittedTasks | undefined> => {
const tasks: DesktopTask[] = [];
for (const path of given.paths) {
const parsed = parseDesktopTask(
await readTaskFile(path, signal),
isPortableBundleName,
);
const parsed = parseDesktopTask(await readTaskFile(path, signal));
if (!parsed.ok)
throw refuse(
`The task file ${path} is refused: ${parsed.error}`,
@@ -166,3 +166,34 @@ it.each([
expect((failure as Error).cause).toBe(reason);
},
);
it("preserves completed views and source absences when a later source read fails", async () => {
const sourceFailure = new Error("cannot read the third retained file");
const failure = await readerViewsOfBytes(
["first", "absent", "third"].map((id) => ({
id,
file: `${id}.txt`,
argv: ["reader", "{file}"],
output: "json" as const,
})),
async ({ id }) => {
if (id === "third") throw sourceFailure;
return id === "absent"
? { kind: "absent" }
: { kind: "bytes", bytes: Buffer.from("input") };
},
async () => ({
exit_code: 0,
stdout: JSON.stringify({ view: { format: "json", view: { value: 7 } } }),
stderr: "",
timed_out: false,
}),
).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
cause: sourceFailure,
diagnostics: {
completed_reader_views: { first: { format: "json", view: { value: 7 } } },
completed_reader_absent: ["absent"],
},
});
});
+15 -3
View File
@@ -88,13 +88,25 @@ export const readerViewsOfBytes = async (
if (readers.length > 0) await processWorkerCleanup.retry();
const absent: string[] = [];
for (const reader of readers) {
const file = await bytesOf(reader);
if (file.kind === "absent") continue;
let file: ReaderFileBytes;
try {
file = await bytesOf(reader);
} catch (cause: unknown) {
throw readerFailure(cause, { views, absent });
}
if (file.kind === "absent") {
absent.push(reader.id);
continue;
}
if (file.kind === "error") {
views.set(reader.id, { format: null, view: null, error: file.error });
continue;
}
const folder = await mkdtemp(join(tmpdir(), "rea-reader-bytes-"));
const folder = await mkdtemp(join(tmpdir(), "rea-reader-bytes-")).catch(
(cause: unknown) => {
throw readerFailure(cause, { views, absent });
},
);
let failure: { readonly cause: unknown } | undefined;
try {
const path = join(folder, reader.file.split("/").at(-1) ?? "file");
@@ -1,3 +1,7 @@
import {
isPortableBundleName,
PORTABLE_BUNDLE_NAME_CONSTRAINT,
} from "../../domain/portableBundleName.js";
import { setImmediate } from "node:timers/promises";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
@@ -15,9 +19,7 @@ import type { EnvironmentBuildReport } from "../../domain/environmentBundleExpor
import { err, ok, type Result } from "../../domain/result.js";
import { inspectAnalysisView } from "../analysisView/AnalysisViewService.js";
import {
BUNDLE_NAME_CONSTRAINT,
ENVIRONMENT_EXPORT_OPERATION,
isPortableBundleName,
planEnvironmentBundle,
registryPackageSource,
type EnvironmentPackageSource,
@@ -190,7 +192,7 @@ const unnamed = (path: string): AnalysisInputError =>
new AnalysisInputError(
ENVIRONMENT_BUILD_OPERATION,
{
userMessage: `The capture's origin is a loopback or IP address, and ${path === "" ? "retained Evidence has no file name to take one from" : `${path} yields no portable environment name (${BUNDLE_NAME_CONSTRAINT})`}; name the environment.`,
userMessage: `The capture's origin is a loopback or IP address, and ${path === "" ? "retained Evidence has no file name to take one from" : `${path} yields no portable environment name (${PORTABLE_BUNDLE_NAME_CONSTRAINT})`}; name the environment.`,
},
[
{
@@ -1,3 +1,4 @@
import { isPortableBundleName } from "../../domain/portableBundleName.js";
import { describe, expect, it } from "vitest";
import { timedCaptureEvidence } from "../../../tests/fixtures/analysisView.js";
@@ -15,7 +16,6 @@ import { PACKAGE_METADATA } from "../../generatedPackageMetadata.js";
import {
BUNDLE_BASE_IMAGE,
bundleDockerfile,
isPortableBundleName,
ENVIRONMENT_EXPORT_OPERATION,
planEnvironmentBundle,
registryPackageSource,
@@ -1,4 +1,8 @@
import { normalizeHttpHostname } from "../../domain/httpHostname.js";
import {
parsePortableBundleName,
PORTABLE_BUNDLE_NAME_PATTERN,
PORTABLE_BUNDLE_NAME_MAX_LENGTH,
} from "../../domain/portableBundleName.js";
import { PRODUCT_IDENTITY } from "../../identity.js";
import { PACKAGE_METADATA } from "../../generatedPackageMetadata.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
@@ -27,18 +31,6 @@ export const BUNDLE_ALLOWED_HOSTS = "127.0.0.1,localhost";
/** Name of the packed CLI inside the env folder when a tarball is exported. */
export const BUNDLE_TARBALL_NAME = "rea-agents.tgz";
/** Folder and env id rule: a kebab-case label the agentenv framework accepts as a local id. */
const BUNDLE_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
// A compose service name is one DNS label, whose wire limit is 63 octets.
const BUNDLE_NAME_MAX_LENGTH = 63;
export const BUNDLE_NAME_CONSTRAINT = `a kebab-case label of at most ${String(BUNDLE_NAME_MAX_LENGTH)} characters, excluding Windows device names, that remains unchanged as an HTTP service hostname`;
/** Win32 reserves these device names for files and folders, so the env folder can never take one. */
const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/u;
/** Whether a name can be the env folder and env id: the checks the export applies. */
export const isPortableBundleName = (name: string): boolean =>
validateBundleName(name).ok;
/** Where the Dockerfile installs the CLI from. */
export type EnvironmentPackageSource =
| { readonly kind: "registry"; readonly specifier: string }
@@ -95,13 +87,13 @@ const nameError = (name: string): AnalysisInputError =>
new AnalysisInputError(
ENVIRONMENT_EXPORT_OPERATION,
{
userMessage: `The bundle name ${JSON.stringify(name)} is not a portable kebab-case label of at most ${String(BUNDLE_NAME_MAX_LENGTH)} characters.`,
userMessage: `The bundle name ${JSON.stringify(name)} is not a portable kebab-case label of at most ${String(PORTABLE_BUNDLE_NAME_MAX_LENGTH)} characters.`,
},
[
{
path: ["name"],
reason: "invalid_format",
expected: BUNDLE_NAME.source,
expected: PORTABLE_BUNDLE_NAME_PATTERN.source,
message:
"The bundle name is the env folder and env id; use lowercase letters, digits and single hyphens, excluding Windows device names.",
},
@@ -128,27 +120,26 @@ const reservedNameError = (name: string): AnalysisInputError =>
const validateBundleName = (
name: string,
): Result<string, AnalysisInputError> => {
if (!BUNDLE_NAME.test(name) || name.length > BUNDLE_NAME_MAX_LENGTH)
return err(nameError(name));
if (WINDOWS_RESERVED_NAME.test(name)) return err(reservedNameError(name));
if (normalizeHttpHostname(name) !== name)
return err(
new AnalysisInputError(
ENVIRONMENT_EXPORT_OPERATION,
const parsed = parsePortableBundleName(name);
if (parsed.ok) return parsed;
if (parsed.error === "format") return err(nameError(name));
if (parsed.error === "reserved") return err(reservedNameError(name));
return err(
new AnalysisInputError(
ENVIRONMENT_EXPORT_OPERATION,
{
userMessage: `The bundle name ${JSON.stringify(name)} cannot be used unchanged as an HTTP host name. Choose a name such as replay-1.`,
},
[
{
userMessage: `The bundle name ${JSON.stringify(name)} cannot be used unchanged as an HTTP host name. Choose a name such as replay-1.`,
path: ["name"],
reason: "invalid_value",
message:
"The service name must remain a hostname rather than be rejected or interpreted as an IP address.",
},
[
{
path: ["name"],
reason: "invalid_value",
message:
"The service name must remain a hostname rather than be rejected or interpreted as an IP address.",
},
],
),
);
return ok(name);
],
),
);
};
const installLine = (source: EnvironmentPackageSource): string =>
+1
View File
@@ -215,6 +215,7 @@ export interface ArtifactReader {
| "dfuse"
| "esp-flash-image"
| "fit"
| "ntfs-mft"
| "file";
entries(
signal?: AbortSignal,
+38 -9
View File
@@ -18,7 +18,10 @@ import {
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import {
artifactReadCancelledBy,
assertArtifactReadActive,
} from "./ArtifactFileOperation.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
@@ -64,12 +67,14 @@ export const regionFileName = (start: number, end: number): string =>
*/
export class DecodedRegionArtifactReader<Image> implements ArtifactReader {
readonly #scope = new ArtifactResourceScope();
readonly #entries = new Map<string, ArtifactEntry>();
readonly #regions = new Map<string, Uint8Array>();
#entries = new Map<string, ArtifactEntry>();
#regions = new Map<string, Uint8Array>();
readonly #streams = new Set<Readable>();
readonly #source: ArtifactFileSource;
readonly #decoding: RegionDecoding<Image>;
#prepared: Promise<void> | undefined;
#prepared:
| { signal: AbortSignal | undefined; promise: Promise<void> }
| undefined;
/** Whole-file facts only; the region map is the sole owner of region bytes. */
#described: Omit<DecodedRegions, "regions"> | undefined;
#closing = false;
@@ -110,8 +115,27 @@ export class DecodedRegionArtifactReader<Image> implements ArtifactReader {
): AsyncIterable<ArtifactEntry> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
this.#prepared ??= this.#prepare(signal);
await this.#prepared;
for (;;) {
const pending = (this.#prepared ??= {
signal,
promise: this.#prepare(signal),
});
try {
await pending.promise;
break;
} catch (cause: unknown) {
if (this.#prepared === pending) this.#prepared = undefined;
if (
pending.signal !== signal &&
signal?.aborted !== true &&
artifactReadCancelledBy(cause, pending.signal)
) {
this.#assertOpen(signal);
continue;
}
throw cause;
}
}
await this.#source.read(signal);
});
const coverage = this.#described?.coverage;
@@ -230,6 +254,8 @@ export class DecodedRegionArtifactReader<Image> implements ArtifactReader {
async #prepare(signal?: AbortSignal): Promise<void> {
const described = this.#decoding.describe(await this.#decode(signal));
const entries = new Map<string, ArtifactEntry>();
const regions = new Map<string, Uint8Array>();
let index = 0;
for (const region of described.regions) {
if (index % 256 === 0) await setImmediate();
@@ -248,13 +274,16 @@ export class DecodedRegionArtifactReader<Image> implements ArtifactReader {
adapterKey: `${this.#decoding.keyPrefix}:${String(index)}`,
formatMetadata: region.formatMetadata,
} satisfies ArtifactEntry;
this.#entries.set(entry.adapterKey, entry);
this.#regions.set(entry.adapterKey, region.bytes);
entries.set(entry.adapterKey, entry);
regions.set(entry.adapterKey, region.bytes);
index += 1;
}
const { regions: _regions, ...facts } = described;
this.#described = facts;
await this.#source.read(signal);
this.#assertOpen(signal);
this.#entries = entries;
this.#regions = regions;
this.#described = facts;
}
async #decode(signal?: AbortSignal): Promise<Image> {
+40
View File
@@ -1,3 +1,4 @@
import { artifactPreparationRecoveryCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
import { getEventListeners, once } from "node:events";
import { readFile, truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -404,6 +405,38 @@ it("keeps the cancellation reason before admission", async () => {
}
});
it("does not publish FIT entries when final source verification fails", async () => {
const path = await writeFit("partial-publication.itb", FIT_EMBEDDED);
const control = new FitArtifactReader(path);
const reader = new FitArtifactReader(path);
const expected = await firstEntry(control);
const nativeRead = ArtifactFileSource.prototype.read;
const physical = Object.assign(
new Error("final source verification failed"),
{ code: "EIO" },
);
let calls = 0;
const read = vi
.spyOn(ArtifactFileSource.prototype, "read")
.mockImplementation(function (this: ArtifactFileSource, ...args) {
calls += 1;
if (calls === 4) return Promise.reject(physical);
return nativeRead.apply(this, args);
});
try {
await expect(firstEntry(reader)).rejects.toBe(physical);
await expect(reader.open(expected)).rejects.toMatchObject({
reason: "integrity",
});
read.mockRestore();
expect((await firstEntry(reader)).path).toBe(expected.path);
} finally {
read.mockRestore();
await reader.close();
await control.close();
}
});
it("keeps the cancellation reason during hash verification", async () => {
const reader = new FitArtifactReader(
await writeFit("hashing.itb", LARGE_FIT),
@@ -430,6 +463,8 @@ it("keeps the cancellation reason during hash verification", async () => {
reader.entries(controller.signal)[Symbol.asyncIterator]().next(),
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
expect(observer).toHaveBeenCalledWith("sha256");
observer.mockRestore();
expect((await firstEntry(reader)).kind).toBe("file");
} finally {
observer.mockRestore();
await reader.close();
@@ -569,3 +604,8 @@ it("preserves a final validation failure when cancellation overlaps it", async (
await reader.close();
}
});
artifactPreparationRecoveryCases({
image: () => FIT_EMBEDDED,
createReader: (path, admitted) => new FitArtifactReader(path, admitted),
});
+34 -7
View File
@@ -13,7 +13,10 @@ import {
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import {
artifactReadCancelledBy,
assertArtifactReadActive,
} from "./ArtifactFileOperation.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import {
createFitDigest,
@@ -30,11 +33,13 @@ const FDT_HEADER_BYTES = 40;
export class FitArtifactReader implements ArtifactReader {
readonly format = "fit" as const;
readonly #scope = new ArtifactResourceScope();
readonly #entries = new Map<string, ArtifactEntry>();
#entries = new Map<string, ArtifactEntry>();
readonly #streams = new Set<Readable>();
readonly #path: string;
readonly #source: ArtifactFileSource;
#prepared: Promise<void> | undefined;
#prepared:
| { signal: AbortSignal | undefined; promise: Promise<void> }
| undefined;
#metadata: FitMetadata | undefined;
#coverage: ArtifactReaderTraversal | undefined;
#closing = false;
@@ -66,8 +71,27 @@ export class FitArtifactReader implements ArtifactReader {
): AsyncIterable<ArtifactEntry> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
this.#prepared ??= this.#prepare(signal);
await this.#prepared;
for (;;) {
const pending = (this.#prepared ??= {
signal,
promise: this.#prepare(signal),
});
try {
await pending.promise;
break;
} catch (cause: unknown) {
if (this.#prepared === pending) this.#prepared = undefined;
if (
pending.signal !== signal &&
signal?.aborted !== true &&
artifactReadCancelledBy(cause, pending.signal)
) {
this.#assertOpen(signal);
continue;
}
throw cause;
}
}
await this.#source.read(signal);
});
if (this.#coverage !== undefined)
@@ -207,6 +231,7 @@ export class FitArtifactReader implements ArtifactReader {
this.#path,
initial.size,
);
const entries = new Map<string, ArtifactEntry>();
let index = 0;
for (const image of structure.images) {
if (index % 256 === 0) await setImmediate();
@@ -228,15 +253,17 @@ export class FitArtifactReader implements ArtifactReader {
adapterKey: `fit:${String(image.index)}`,
formatMetadata: image.metadata,
} satisfies ArtifactEntry;
this.#entries.set(entry.adapterKey, entry);
entries.set(entry.adapterKey, entry);
}
await this.#source.read(signal);
this.#assertOpen(signal);
this.#entries = entries;
this.#metadata = structure.metadata;
if (structure.limitations.length > 0)
this.#coverage = {
status: "complete",
limitations: structure.limitations,
};
await this.#source.read(signal);
}
/** One streamed pass per image feeds every supported digest. */
@@ -1,3 +1,6 @@
import { artifactPreparationRecoveryCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { openRegularFile } from "../filesystem/RegularFile.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -159,6 +162,72 @@ it("settles an active region stream when closed", async () => {
}
});
it("retries decoded-region preparation cancelled while reading", async () => {
const path = await writeImage("retry.hex", INTEL_HEX_I32_GAP);
const admitted = await openRegularFile(path, { symlinks: "reject" });
const reader = new HexRecordArtifactReader(path, "intel-hex", admitted);
const controller = new AbortController();
const reason = { stage: "decoded region read" };
const nativeRead = admitted.handle.read.bind(admitted.handle);
const read = vi.spyOn(admitted.handle, "read").mockImplementation((async (
...args: unknown[]
) => {
const result = await Reflect.apply(nativeRead, admitted.handle, args);
controller.abort(reason);
return result;
}) as typeof admitted.handle.read);
try {
await expect(
reader.entries(controller.signal)[Symbol.asyncIterator]().next(),
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
read.mockRestore();
expect(
(await reader.entries()[Symbol.asyncIterator]().next()).value,
).toMatchObject({ kind: "file" });
} finally {
read.mockRestore();
await reader.close();
await admitted.handle.close();
}
});
it("does not publish decoded regions when final source verification fails", async () => {
const path = await writeImage("partial.hex", INTEL_HEX_I32_GAP);
const control = new HexRecordArtifactReader(path, "intel-hex");
const reader = new HexRecordArtifactReader(path, "intel-hex");
const expected = (await control.entries()[Symbol.asyncIterator]().next())
.value!;
const nativeRead = ArtifactFileSource.prototype.read;
const physical = Object.assign(
new Error("final source verification failed"),
{ code: "EIO" },
);
let calls = 0;
const read = vi
.spyOn(ArtifactFileSource.prototype, "read")
.mockImplementation(function (this: ArtifactFileSource, ...args) {
calls += 1;
if (calls === 2) return Promise.reject(physical);
return nativeRead.apply(this, args);
});
try {
await expect(reader.entries()[Symbol.asyncIterator]().next()).rejects.toBe(
physical,
);
await expect(reader.open(expected)).rejects.toMatchObject({
reason: "integrity",
});
read.mockRestore();
expect(
(await reader.entries()[Symbol.asyncIterator]().next()).value,
).toMatchObject({ path: expected.path });
} finally {
read.mockRestore();
await reader.close();
await control.close();
}
});
it("honors cancellation before admitting a file with the exact reason", async () => {
const reader = new HexRecordArtifactReader(
await writeImage("cancel.hex", INTEL_HEX_I32_GAP),
@@ -337,3 +406,9 @@ it("bounds copied region chunks and isolates cached bytes across opens", async (
await reader.close();
}
});
artifactPreparationRecoveryCases({
image: () => Buffer.from(INTEL_HEX_I32_GAP),
createReader: (path, admitted) =>
new HexRecordArtifactReader(path, "intel-hex", admitted),
});
+211
View File
@@ -0,0 +1,211 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import { NtfsMftArtifactReader } from "./NtfsMftArtifactReader.js";
import { MFT_DEFAULT_RECORD_BYTES } from "../domain/windows/ntfsMft.js";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js";
/** A 1 KiB FILE record whose update sequence array covers both sectors. */
const recordBytes = (options: {
readonly sequenceNumber?: number;
readonly flags?: number;
readonly index?: number;
}): Buffer => {
const record = Buffer.alloc(MFT_DEFAULT_RECORD_BYTES);
record.write("FILE", 0, "latin1");
const sequenceNumber = options.sequenceNumber ?? 1;
record.writeUInt16LE(48, 4);
record.writeUInt16LE(3, 6);
record.writeUInt16LE(sequenceNumber, 48);
record.writeUInt16LE(0xa5a5, 50);
record.writeUInt16LE(0xa5a5, 52);
record.writeUInt16LE(sequenceNumber, 16);
record.writeUInt16LE(1, 18);
record.writeUInt32LE(options.index ?? 0, 44);
record.writeUInt16LE(56, 20);
record.writeUInt16LE(options.flags ?? 0x0001, 22);
record.writeUInt32LE(64, 24);
record.writeUInt32LE(0xffff_ffff, 56);
record.writeUInt32LE(MFT_DEFAULT_RECORD_BYTES, 28);
record.writeUInt16LE(sequenceNumber, 510);
record.writeUInt16LE(sequenceNumber, 1022);
return record;
};
const writeMft = async (name: string, bytes: Buffer): Promise<string> => {
const directory = await createTestTempDirectory("rea-ntfs-mft-");
const path = join(directory, name);
await writeFile(path, bytes);
return path;
};
it("reports a $MFT stream's record headers as the root occurrence", async () => {
const inventory = await scanCanonicalArtifactInventory(
await writeMft(
"$MFT",
Buffer.concat([
recordBytes({}),
recordBytes({ flags: 0x0003, index: 1 }),
]),
),
);
expect(inventory.manifest.root_format).toBe("ntfs-mft");
expect(inventory.coverage.status).toBe("complete");
// A record stream declares no members, so the root is its whole inventory.
expect(inventory.occurrences.map((row) => row.logical_path)).toEqual(["."]);
expect(inventory.occurrences[0]).toMatchObject({
artifact_format: "ntfs-mft",
format_metadata: {
kind: "ntfs-mft",
record_bytes: MFT_DEFAULT_RECORD_BYTES,
record_count: 2,
in_use_record_count: 2,
directory_record_count: 1,
extension_record_count: 0,
fixup_mismatch_count: 0,
fixup_unverified_record_count: 0,
truncated_tail_bytes: 0,
},
});
});
it("names a failed fixup in the coverage limitations", async () => {
const record = recordBytes({ sequenceNumber: 4 });
// A trailer that is not the sequence number marks the sector as not cleanly written.
record.writeUInt16LE(0x1234, 510);
const inventory = await scanCanonicalArtifactInventory(
await writeMft("$MFT", record),
);
expect(inventory.manifest.root_format).toBe("ntfs-mft");
expect(inventory.coverage.status).toBe("unknown");
expect(inventory.limitations).toContainEqual(
expect.stringMatching(/sector trailer that is not the update sequence/u),
);
});
it("reports an unaligned used-byte count as incomplete coverage", async () => {
const record = recordBytes({});
record.writeUInt32LE(57, 24);
const inventory = await scanCanonicalArtifactInventory(
await writeMft("$MFT", record),
);
expect(inventory.coverage.status).toBe("unknown");
expect(inventory.occurrences[0]?.format_metadata).toMatchObject({
record_headers: [{ usedBytes: 57, extentValid: false }],
});
});
it("reports incomplete coverage when FILE extents contradict the record slots", async () => {
const usedTooLarge = recordBytes({});
usedTooLarge.writeUInt32LE(4096, 24);
const totalTooSmall = recordBytes({});
totalTooSmall.writeUInt32LE(512, 28);
const inventory = await scanCanonicalArtifactInventory(
await writeMft("$MFT", Buffer.concat([usedTooLarge, totalTooSmall])),
);
expect(inventory.coverage.status).toBe("unknown");
expect(inventory.limitations).toContainEqual(
"2 FILE record(s) declare inconsistent record extents, beginning at offset 0",
);
expect(inventory.occurrences[0]?.format_metadata).toMatchObject({
record_count: 2,
fixup_mismatch_count: 0,
fixup_unverified_record_count: 0,
});
});
it("retries after final source verification fails without publishing its metadata", async () => {
const reader = new NtfsMftArtifactReader(
await writeMft("$MFT", recordBytes({})),
);
const read = ArtifactFileSource.prototype.read;
const spy = vi
.spyOn(ArtifactFileSource.prototype, "read")
.mockImplementationOnce(function (this: ArtifactFileSource, signal) {
return read.call(this, signal);
})
.mockRejectedValueOnce(new Error("final source verification failed"));
try {
await expect(
reader.entries()[Symbol.asyncIterator]().next(),
).rejects.toThrow("final source verification failed");
expect(reader.formatMetadata()).toBeUndefined();
await expect(
reader.entries()[Symbol.asyncIterator]().next(),
).resolves.toMatchObject({
done: true,
});
expect(reader.formatMetadata()).toMatchObject({
kind: "ntfs-mft",
record_count: 1,
});
} finally {
spy.mockRestore();
await reader.close();
}
});
it("retries a shared preparation cancelled by another traversal", async () => {
const reader = new NtfsMftArtifactReader(
await writeMft("$MFT", recordBytes({})),
);
const controller = new AbortController();
let entered: () => void = () => {};
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const read = ArtifactFileSource.prototype.read;
const spy = vi
.spyOn(ArtifactFileSource.prototype, "read")
.mockImplementationOnce(async function (this: ArtifactFileSource, signal) {
entered();
await new Promise<void>((resolve) => {
signal?.addEventListener("abort", () => resolve(), { once: true });
});
assertArtifactReadActive(signal);
return read.call(this, signal);
});
try {
const cancelled = reader
.entries(controller.signal)
[Symbol.asyncIterator]()
.next();
const cancelledResult = expect(cancelled).rejects.toMatchObject({
reason: "cancelled",
});
await started;
const other = reader.entries()[Symbol.asyncIterator]().next();
controller.abort("cancelled first traversal");
await cancelledResult;
await expect(other).resolves.toMatchObject({ done: true });
expect(reader.formatMetadata()).toMatchObject({ record_count: 1 });
} finally {
controller.abort();
spy.mockRestore();
await reader.close();
}
});
it("revalidates the source before reusing a completed header inventory", async () => {
const path = await writeMft("$MFT", recordBytes({}));
const reader = new NtfsMftArtifactReader(path);
try {
await reader.entries()[Symbol.asyncIterator]().next();
await writeFile(
path,
Buffer.concat([recordBytes({}), recordBytes({ index: 1 })]),
);
await expect(
reader.entries()[Symbol.asyncIterator]().next(),
).rejects.toMatchObject({ reason: "integrity" });
} finally {
await reader.close();
}
});
+174
View File
@@ -0,0 +1,174 @@
import type { Readable } from "node:stream";
import {
ntfsMftMetadataSchema,
type ArtifactFormatMetadata,
} from "../domain/artifactFormatMetadata.js";
import type { RegionDecodeFailure } from "../domain/firmware/regionDecoder.js";
import {
createMftDecoder,
type MftInventory,
} from "../domain/windows/ntfsMft.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
type ArtifactReaderTraversal,
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import {
artifactReadCancelledBy,
assertArtifactReadActive,
} from "./ArtifactFileOperation.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
/**
* An MFT stream is its own content: the FILE records describe the source
* volume, not members inside the stream, so header facts are attached to
* the root occurrence.
*/
export class NtfsMftArtifactReader implements ArtifactReader {
readonly format = "ntfs-mft" as const;
readonly #scope = new ArtifactResourceScope();
readonly #source: ArtifactFileSource;
#prepared:
| { signal: AbortSignal | undefined; promise: Promise<void> }
| undefined;
#metadata: ArtifactFormatMetadata | undefined;
#limitations: readonly string[] = [];
#closing = false;
constructor(path: string, admitted?: StableRegularFileDescriptor) {
this.#source = new ArtifactFileSource(path, "$MFT stream", admitted);
}
formatMetadata(): ArtifactFormatMetadata | undefined {
return this.#metadata === undefined
? undefined
: structuredClone(this.#metadata);
}
async prepareContainer(
expectedSha256: string,
signal?: AbortSignal,
): Promise<void> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
await this.#source.bindSha256(expectedSha256, signal);
});
}
async *entries(
signal?: AbortSignal,
options?: ArtifactTraversalOptions,
): AsyncIterable<ArtifactEntry> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
for (;;) {
const pending = (this.#prepared ??= {
signal,
promise: this.#prepare(signal),
});
try {
await pending.promise;
break;
} catch (cause: unknown) {
if (this.#prepared === pending) this.#prepared = undefined;
if (
pending.signal !== signal &&
signal?.aborted !== true &&
artifactReadCancelledBy(cause, pending.signal)
) {
this.#assertOpen(signal);
continue;
}
throw cause;
}
}
this.#assertOpen(signal);
await this.#source.read(signal);
});
// An MFT declares no members, so the root occurrence is the whole
// inventory; the coverage callback reports what its parse did not establish.
options?.onCoverage?.(coverageOf(this.#limitations));
}
async open(entry: ArtifactEntry, _signal?: AbortSignal): Promise<Readable> {
return this.#scope.run(async () => {
throw new ArtifactReaderFailure(
"unavailable",
`$MFT stream declares no member to open for ${entry.path}`,
);
});
}
async close(): Promise<void> {
this.#closing = true;
await this.#scope.close();
await this.#source.close();
this.#metadata = undefined;
}
provenance(): readonly [] {
return [];
}
#assertOpen(signal?: AbortSignal): void {
assertArtifactReadActive(signal);
if (this.#closing)
throw new ArtifactReaderFailure(
"unavailable",
"$MFT stream reader is closed",
);
}
async #prepare(signal?: AbortSignal): Promise<void> {
const image = await this.#decode(signal);
await this.#source.read(signal);
this.#metadata = ntfsMftMetadataSchema.parse(image.metadata);
this.#limitations = image.limitations;
}
async #decode(signal?: AbortSignal): Promise<MftInventory> {
const { handle, initial } = await this.#source.read(signal);
const decoder = createMftDecoder(initial.size);
if (!decoder.ok) throw this.#failure(decoder.error);
if (initial.size > 0)
for await (const chunk of readFileHandleChunks(handle, {
end: initial.size - 1,
signal,
cancellationFailure: (reason) =>
new ArtifactReaderFailure("cancelled", "$MFT stream read cancelled", {
cause: reason,
}),
}) as AsyncIterable<Buffer>) {
this.#assertOpen(signal);
const written = decoder.value.write(chunk);
if (!written.ok) throw this.#failure(written.error);
}
const image = decoder.value.finish();
if (!image.ok) throw this.#failure(image.error);
return image.value;
}
#failure(failure: RegionDecodeFailure): ArtifactReaderFailure {
return failure.kind === "format"
? new ArtifactReaderFailure(
"format",
`$MFT stream is malformed: ${failure.message}`,
)
: new ArtifactReaderFailure(
"limit",
`$MFT stream exceeds a fixed limit: ${failure.message}`,
failure.boundary === undefined ? {} : { boundary: failure.boundary },
);
}
}
const coverageOf = (limitations: readonly string[]): ArtifactReaderTraversal =>
limitations.length === 0
? { status: "complete", limitations: [] }
: { status: "unknown", limitations };
@@ -1,4 +1,7 @@
import { artifactReaderLifecycleCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
import {
artifactPreparationRecoveryCases,
artifactReaderLifecycleCases,
} from "../../tests/fixtures/artifactReaderLifecycle.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { buffer } from "node:stream/consumers";
@@ -91,6 +94,14 @@ it("preserves cancellation during payload CRC admission", async () => {
}
})(),
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
reads.mockRestore();
const recovered = await entries(reader);
expect(recovered).toHaveLength(1);
expect(
(await buffer(await reader.open(recovered[0]!))).equals(
Buffer.alloc(128 * 1024, 0x61),
),
).toBe(true);
} finally {
await reader.close();
reads.mockRestore();
@@ -205,3 +216,8 @@ it("reports impossible over-cap component extents as malformed", async () => {
await reader.close();
}
});
artifactPreparationRecoveryCases({
image: () => buildUImage({ payload: Buffer.from("payload") }),
createReader: (path, admitted) => new UImageArtifactReader(path, admitted),
});
+28 -4
View File
@@ -8,7 +8,10 @@ import type {
UImageMetadata,
} from "../domain/artifactFormatMetadata.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import {
artifactReadCancelledBy,
assertArtifactReadActive,
} from "./ArtifactFileOperation.js";
import {
ArtifactReaderFailure,
copyArtifactEntry,
@@ -47,7 +50,9 @@ export class UImageArtifactReader implements ArtifactReader {
readonly #entries = new Map<string, UImageEntry>();
readonly #streams = new Set<Readable>();
readonly #source: ArtifactFileSource;
#prepared: Promise<void> | undefined;
#prepared:
| { signal: AbortSignal | undefined; promise: Promise<void> }
| undefined;
#header: UImageMetadata | undefined;
#closing = false;
@@ -75,8 +80,27 @@ export class UImageArtifactReader implements ArtifactReader {
): AsyncIterable<ArtifactEntry> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
this.#prepared ??= this.#prepare(signal);
await this.#prepared;
for (;;) {
const pending = (this.#prepared ??= {
signal,
promise: this.#prepare(signal),
});
try {
await pending.promise;
break;
} catch (cause: unknown) {
if (this.#prepared === pending) this.#prepared = undefined;
if (
pending.signal !== signal &&
signal?.aborted !== true &&
artifactReadCancelledBy(cause, pending.signal)
) {
this.#assertOpen(signal);
continue;
}
throw cause;
}
}
await this.#source.read(signal);
});
this.#assertOpen(signal);
@@ -1,3 +1,5 @@
import { artifactPreparationRecoveryCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { buffer, text } from "node:stream/consumers";
@@ -43,6 +45,68 @@ const repeatedBlock = (data: Buffer): Buffer => {
]);
};
it("retries UnityFs preparation cancelled during file reading", async () => {
const path = await fixture(buildUnityFs([{ path: "a", data: "x" }]));
const admitted = await openRegularFile(path, { symlinks: "reject" });
const reader = new UnityFsArtifactReader(path, admitted);
const controller = new AbortController();
const reason = { stage: "header read" };
const nativeRead = admitted.handle.read.bind(admitted.handle);
const read = vi.spyOn(admitted.handle, "read").mockImplementation((async (
...args: unknown[]
) => {
const result = await Reflect.apply(nativeRead, admitted.handle, args);
controller.abort(reason);
return result;
}) as typeof admitted.handle.read);
try {
await expect(
(async () => {
for await (const _ of reader.entries(controller.signal)) {
}
})(),
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
read.mockRestore();
expect((await entries(reader)).map((entry) => entry.path)).toEqual(["a"]);
} finally {
read.mockRestore();
await reader.close();
await admitted.handle.close();
}
});
it("does not publish UnityFs entries when final source verification fails", async () => {
const path = await fixture(buildUnityFs([{ path: "a", data: "x" }]));
const control = new UnityFsArtifactReader(path);
const reader = new UnityFsArtifactReader(path);
const expected = (await entries(control))[0]!;
const nativeRead = ArtifactFileSource.prototype.read;
const physical = Object.assign(
new Error("final source verification failed"),
{ code: "EIO" },
);
let calls = 0;
const read = vi
.spyOn(ArtifactFileSource.prototype, "read")
.mockImplementation(function (this: ArtifactFileSource, ...args) {
calls += 1;
if (calls === 2) return Promise.reject(physical);
return nativeRead.apply(this, args);
});
try {
await expect(entries(reader)).rejects.toBe(physical);
await expect(reader.open(expected)).rejects.toMatchObject({
reason: "integrity",
});
read.mockRestore();
expect((await entries(reader)).map((entry) => entry.path)).toEqual(["a"]);
} finally {
read.mockRestore();
await reader.close();
await control.close();
}
});
describe("UnityFS allocation and malformed-input boundaries", () => {
it("rejects an oversized directory extending past the physical file", async () => {
const bytes = buildUnityFs([{ path: "data", data: "x" }]);
@@ -431,3 +495,8 @@ describe("UnityFS stream capacity and cache ownership", () => {
}
});
});
artifactPreparationRecoveryCases({
image: () => buildUnityFs([{ path: "a", data: "x" }]),
createReader: (path, admitted) => new UnityFsArtifactReader(path, admitted),
});
+65 -24
View File
@@ -12,7 +12,10 @@ import {
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import {
artifactReadCancelledBy,
assertArtifactReadActive,
} from "./ArtifactFileOperation.js";
import { readArtifactFileBytes } from "./ArtifactFileRange.js";
import type {
ArtifactFormatMetadata,
@@ -52,10 +55,12 @@ interface UnityFsEntryState {
export class UnityFsArtifactReader implements ArtifactReader {
readonly format = "unityfs" as const;
readonly #scope = new ArtifactResourceScope();
readonly #entries = new Map<string, UnityFsEntryState>();
#entries = new Map<string, UnityFsEntryState>();
readonly #streams = new Map<Readable, AbortController>();
readonly #source: ArtifactFileSource;
#prepared: Promise<void> | undefined;
#prepared:
| { signal: AbortSignal | undefined; promise: Promise<void> }
| undefined;
#header: UnityFsMetadata | undefined;
#blocks: readonly UnityFsBlock[] = [];
#dataStart = 0;
@@ -88,8 +93,27 @@ export class UnityFsArtifactReader implements ArtifactReader {
): AsyncIterable<ArtifactEntry> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
this.#prepared ??= this.#prepare(signal);
await this.#prepared;
for (;;) {
const pending = (this.#prepared ??= {
signal,
promise: this.#prepare(signal),
});
try {
await pending.promise;
break;
} catch (cause: unknown) {
if (this.#prepared === pending) this.#prepared = undefined;
if (
pending.signal !== signal &&
signal?.aborted !== true &&
artifactReadCancelledBy(cause, pending.signal)
) {
this.#assertOpen(signal);
continue;
}
throw cause;
}
}
await this.#source.read(signal);
});
this.#assertOpen(signal);
@@ -229,7 +253,7 @@ export class UnityFsArtifactReader implements ArtifactReader {
if (header === undefined)
throw unityFsFormatFailure("no complete UnityFS header");
const status = header.layout.status;
this.#header = {
const metadata: UnityFsMetadata = {
kind: "unityfs",
signature: "UnityFS",
format_version: header.formatVersion,
@@ -245,7 +269,12 @@ export class UnityFsArtifactReader implements ArtifactReader {
data_hash: null,
directory_status: status,
};
if (status !== "available") return;
if (status !== "available") {
await this.#source.read(signal);
this.#assertOpen(signal);
this.#header = metadata;
return;
}
const { dataHash, blocks, nodes, dataStart } = await readUnityFsBlocksInfo(
handle,
header,
@@ -259,44 +288,55 @@ export class UnityFsArtifactReader implements ArtifactReader {
if (streamBytes > BigInt(budget))
throw expansionLimit("declared virtual stream", streamBytes, budget);
}
this.#header = {
...this.#header,
const preparedMetadata: UnityFsMetadata = {
...metadata,
data_hash: dataHash,
block_count: blocks.length,
data_start: dataStart,
};
this.#dataStart = dataStart;
// Keep the source block count above, but do not revisit zero-output rows
// for every member. Parsed stream/compressed offsets remain authoritative.
this.#blocks = blocks.filter((block) => block.uncompressedSize > 0);
this.#remainingDecodeBytes = budget;
await this.#registerNodes(nodes, budget, signal);
const readableBlocks = blocks.filter((block) => block.uncompressedSize > 0);
const registered = await this.#registerNodes(
nodes,
readableBlocks,
budget,
signal,
);
await this.#source.read(signal);
this.#assertOpen(signal);
this.#header = preparedMetadata;
this.#dataStart = dataStart;
this.#blocks = readableBlocks;
this.#remainingDecodeBytes = budget;
this.#entries = registered.entries;
this.#remainingReadOperations = registered.remainingReadOperations;
}
async #registerNodes(
nodes: readonly UnityFsNode[],
blocks: readonly UnityFsBlock[],
budget: number,
signal?: AbortSignal,
): Promise<void> {
): Promise<{
entries: Map<string, UnityFsEntryState>;
remainingReadOperations: number;
}> {
const entries = new Map<string, UnityFsEntryState>();
let readableBytes = 0n;
for (let index = 0; index < nodes.length; index++) {
if (index % 256 === 0) await setImmediate();
this.#assertOpen(signal);
const node = nodes[index]!;
const firstBlock =
node.size === 0 ? -1 : blockEndingAfter(this.#blocks, node.offset);
node.size === 0 ? -1 : blockEndingAfter(blocks, node.offset);
const lastBlock =
node.size === 0
? -1
: blockEndingAfter(this.#blocks, node.offset + node.size - 1);
: blockEndingAfter(blocks, node.offset + node.size - 1);
if (node.size !== 0 && (firstBlock < 0 || lastBlock < firstBlock))
throw unityFsFormatFailure("member has no block range");
const unavailable = firstUnavailableBlock(
this.#blocks,
firstBlock,
lastBlock,
);
const unavailable = firstUnavailableBlock(blocks, firstBlock, lastBlock);
const kind =
(node.flags & 1) !== 0 ? ("directory" as const) : ("file" as const);
if (kind === "file" && unavailable === undefined) {
@@ -331,7 +371,7 @@ export class UnityFsArtifactReader implements ArtifactReader {
flags: node.flags,
},
} satisfies UnityFsEntry;
this.#entries.set(adapterKey, {
entries.set(adapterKey, {
entry,
firstBlock,
lastBlock,
@@ -340,14 +380,15 @@ export class UnityFsArtifactReader implements ArtifactReader {
}
// Four ordinary passes over admitted blocks, nodes and plaintext chunks,
// with a small-reader floor. Byte quotas alone cannot bound tiny-block I/O.
this.#remainingReadOperations =
const remainingReadOperations =
4 *
Math.max(
1024,
this.#blocks.length +
blocks.length +
nodes.length +
Math.ceil(Number(readableBytes) / CHUNK_BYTES),
);
return { entries, remainingReadOperations };
}
async *#memberChunks(
@@ -1,3 +1,5 @@
import { artifactPreparationRecoveryCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { once } from "node:events";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -26,6 +28,68 @@ const entries = async (reader: WxapkgArtifactReader) => {
return result;
};
it("retries Wxapkg preparation cancelled during file reading", async () => {
const path = await fixture(buildWxapkg([{ path: "a", data: "x" }]));
const admitted = await openRegularFile(path, { symlinks: "reject" });
const reader = new WxapkgArtifactReader(path, admitted);
const controller = new AbortController();
const reason = { stage: "header read" };
const nativeRead = admitted.handle.read.bind(admitted.handle);
const read = vi.spyOn(admitted.handle, "read").mockImplementation((async (
...args: unknown[]
) => {
const result = await Reflect.apply(nativeRead, admitted.handle, args);
controller.abort(reason);
return result;
}) as typeof admitted.handle.read);
try {
await expect(
(async () => {
for await (const _ of reader.entries(controller.signal)) {
}
})(),
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
read.mockRestore();
expect((await entries(reader)).map((entry) => entry.path)).toEqual(["a"]);
} finally {
read.mockRestore();
await reader.close();
await admitted.handle.close();
}
});
it("does not publish Wxapkg entries when final source verification fails", async () => {
const path = await fixture(buildWxapkg([{ path: "a", data: "x" }]));
const control = new WxapkgArtifactReader(path);
const reader = new WxapkgArtifactReader(path);
const expected = (await entries(control))[0]!;
const nativeRead = ArtifactFileSource.prototype.read;
const physical = Object.assign(
new Error("final source verification failed"),
{ code: "EIO" },
);
let calls = 0;
const read = vi
.spyOn(ArtifactFileSource.prototype, "read")
.mockImplementation(function (this: ArtifactFileSource, ...args) {
calls += 1;
if (calls === 2) return Promise.reject(physical);
return nativeRead.apply(this, args);
});
try {
await expect(entries(reader)).rejects.toBe(physical);
await expect(reader.open(expected)).rejects.toMatchObject({
reason: "integrity",
});
read.mockRestore();
expect((await entries(reader)).map((entry) => entry.path)).toEqual(["a"]);
} finally {
read.mockRestore();
await reader.close();
await control.close();
}
});
describe("wxapkg allocation and malformed-input boundaries", () => {
it("admits the encoded table budget before reading it", async () => {
const bytes = buildWxapkg([{ path: "a", data: "x" }]);
@@ -308,3 +372,8 @@ describe("wxapkg stream capacity and freshness", () => {
}
});
});
artifactPreparationRecoveryCases({
image: () => buildWxapkg([{ path: "a", data: "x" }]),
createReader: (path, admitted) => new WxapkgArtifactReader(path, admitted),
});
+44 -10
View File
@@ -12,7 +12,10 @@ import {
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import {
artifactReadCancelledBy,
assertArtifactReadActive,
} from "./ArtifactFileOperation.js";
import { readArtifactFileBytes } from "./ArtifactFileRange.js";
import type {
ArtifactFormatMetadata,
@@ -48,10 +51,12 @@ interface WxapkgEntryState {
export class WxapkgArtifactReader implements ArtifactReader {
readonly format = "wxapkg" as const;
readonly #scope = new ArtifactResourceScope();
readonly #entries = new Map<string, WxapkgEntryState>();
#entries = new Map<string, WxapkgEntryState>();
readonly #streams = new Map<Readable, AbortController>();
readonly #source: ArtifactFileSource;
#prepared: Promise<void> | undefined;
#prepared:
| { signal: AbortSignal | undefined; promise: Promise<void> }
| undefined;
#header: WxapkgMetadata | undefined;
#remainingReadOperations = 0;
#admittedReadOperations = 0;
@@ -81,8 +86,27 @@ export class WxapkgArtifactReader implements ArtifactReader {
): AsyncIterable<ArtifactEntry> {
await this.#scope.run(async () => {
this.#assertOpen(signal);
this.#prepared ??= this.#prepare(signal);
await this.#prepared;
for (;;) {
const pending = (this.#prepared ??= {
signal,
promise: this.#prepare(signal),
});
try {
await pending.promise;
break;
} catch (cause: unknown) {
if (this.#prepared === pending) this.#prepared = undefined;
if (
pending.signal !== signal &&
signal?.aborted !== true &&
artifactReadCancelledBy(cause, pending.signal)
) {
this.#assertOpen(signal);
continue;
}
throw cause;
}
}
await this.#source.read(signal);
});
this.#assertOpen(signal);
@@ -201,7 +225,7 @@ export class WxapkgArtifactReader implements ArtifactReader {
const header = await readWxapkgHeader(handle, initial.size, signal);
if (header === undefined)
throw wxapkgFormatFailure("no complete wxapkg header");
this.#header = {
const metadata: WxapkgMetadata = {
kind: "wxapkg",
info: header.layout.status === "available" ? header.info : null,
index_length:
@@ -212,7 +236,12 @@ export class WxapkgArtifactReader implements ArtifactReader {
header.layout.status === "available" ? header.fileCount : null,
directory_status: header.layout.status,
};
if (header.layout.status !== "available") return;
if (header.layout.status !== "available") {
await this.#source.read(signal);
this.#assertOpen(signal);
this.#header = metadata;
return;
}
const { members } = await readWxapkgFileTable(
handle,
header,
@@ -220,6 +249,7 @@ export class WxapkgArtifactReader implements ArtifactReader {
signal,
);
const budget = artifactExpansionBudgetBytes(initial.size);
const entries = new Map<string, WxapkgEntryState>();
let declaredBytes = 0n;
for (let index = 0; index < members.length; index++) {
if (index % 256 === 0) await setImmediate();
@@ -234,7 +264,7 @@ export class WxapkgArtifactReader implements ArtifactReader {
{ boundary: "memory" },
);
const adapterKey = `wxapkg-entry:${String(index)}`;
this.#entries.set(adapterKey, {
entries.set(adapterKey, {
entry: {
path: member.path,
sourcePath: member.declaredPath,
@@ -260,14 +290,18 @@ export class WxapkgArtifactReader implements ArtifactReader {
});
}
// Header, table and per-chunk member reads; a small-reader floor applies.
this.#admittedReadOperations =
const admittedReadOperations =
4 *
Math.max(
1024,
members.length + Math.ceil(Number(declaredBytes) / CHUNK_BYTES),
);
this.#remainingReadOperations = this.#admittedReadOperations;
await this.#source.read(signal);
this.#assertOpen(signal);
this.#header = metadata;
this.#entries = entries;
this.#admittedReadOperations = admittedReadOperations;
this.#remainingReadOperations = admittedReadOperations;
}
async *#memberChunks(
+2 -1
View File
@@ -43,7 +43,8 @@ type FormatsWithReaders =
| "uf2"
| "dfuse"
| "esp-flash-image"
| "fit";
| "fit"
| "ntfs-mft";
const readerFormatsMatch: Equal<ArtifactReaderFormat, FormatsWithReaders> =
true;
+9
View File
@@ -40,6 +40,7 @@ import { NodeSeaArtifactReader } from "./NodeSeaArtifactReader.js";
import type { PyInstallerAdmission } from "./pyinstaller/PyInstallerAdmission.js";
import { PyInstallerArtifactReader } from "./PyInstallerArtifactReader.js";
import { Uf2ArtifactReader } from "./Uf2ArtifactReader.js";
import { NtfsMftArtifactReader } from "./NtfsMftArtifactReader.js";
import { UImageArtifactReader } from "./UImageArtifactReader.js";
import { UnityFsArtifactReader } from "./UnityFsArtifactReader.js";
import { WxapkgArtifactReader } from "./WxapkgArtifactReader.js";
@@ -465,6 +466,14 @@ const NON_ZIP_FORMATS = {
createReader: (path, options) =>
new FitArtifactReader(path, sourceOf(options)),
}),
"ntfs-mft": described("ntfs-mft", {
...plain,
retainClassifiedSource: true,
readerLimitation:
"MFT inventory reports whole-stream counts and a bounded sample of the first 32 decoded FILE record headers, with the omitted-header count. Attributes, filenames, data streams and the $UsnJrnl:$J journal are not decoded, so no path, file size or change history is established.",
createReader: (path, options) =>
new NtfsMftArtifactReader(path, sourceOf(options)),
}),
unknown: described("unknown", plain),
} satisfies Record<
Exclude<ArtifactFormatId, ZipPackageFormat>,
@@ -576,6 +576,28 @@ it("classifies nested UF2 by block magics and DfuSe by prefix and suffix", () =>
).toMatchObject({ format: "file" });
});
it("classifies a $MFT stream by its FILE record header, under any name", () => {
const mft = Buffer.alloc(2_048);
mft.write("FILE", 0, "latin1");
mft.writeUInt32LE(1024, 28);
for (const path of ["evidence/$MFT", "evidence/mft.raw", "evidence/records"])
expect(classifyArtifactBytesAtPath(path, mft)).toEqual({
kind: "executable",
format: "ntfs-mft",
});
});
it("leaves plain content beginning with FILE unclassified as MFT", () => {
const text = Buffer.from(
"FILE is a plain text prefix, not an NTFS record header",
);
expect(
classifyArtifactBytesAtPath("evidence/readme.txt", text),
).toMatchObject({
format: "file",
});
});
it("classifies a FIT by a /images node within the first 4 KiB", () => {
const images = [{ name: "kernel", data: Buffer.from("kernel") }];
const late = devicetreeFixture({
@@ -11,6 +11,7 @@ import { recognizeEspImage } from "../../domain/firmware/espImage.js";
import { hasUf2Block } from "../../domain/firmware/uf2.js";
import { isDfuSeFile } from "../../domain/firmware/dfuse.js";
import { hasFitImagesNode } from "../../domain/firmware/fitImage.js";
import { hasMftFileRecordHeader } from "../../domain/windows/ntfsMft.js";
import type { ArtifactClassificationEvidence } from "../ArtifactClassificationProbe.js";
import { asarHeaderAdmissionFailure } from "../AsarHeader.js";
import { hasDestinationPath } from "../ArtifactPaths.js";
@@ -622,6 +623,7 @@ export const classifyArtifactBytes = (
return "dfuse";
if (recognizeEspImage(prefix, fileSize) === "esp-image") return "esp-image";
if (hasFitImagesNode(prefix)) return "fit";
if (hasMftFileRecordHeader(prefix)) return "ntfs-mft";
if (hasBinaryPlistSignature(prefix)) return "plist";
if (hasXmlPlistSignature(prefix)) return "plist";
const fatFormat = classifyFatArtifact(evidence, fileSize);
+4 -4
View File
@@ -1,3 +1,4 @@
import { portableBundleNameSchema } from "../domain/portableBundleName.js";
import { z } from "zod";
import { absoluteLocalPathStringSchema } from "../domain/localPath.js";
@@ -42,10 +43,9 @@ export const MEASURE_BUILD_TASK_CONTRACT = {
bundle: absoluteLocalPathStringSchema.describe(
"The exported bundle's folder on this host.",
),
task: z
.string()
.min(1)
.describe("The task's name, as its tasks/<name>.json names it."),
task: portableBundleNameSchema.describe(
"The task's name, as its tasks/<name>.json names it.",
),
model: z
.string()
.min(1)
@@ -1,6 +1,7 @@
import { execFile } from "node:child_process";
import { constants } from "node:fs";
import {
chmod,
mkdir,
open,
readFile,
@@ -67,6 +68,75 @@ const readFacts = async (
}
};
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"keeps disk and archive permission failures distinct from missing paths",
async () => {
const root = await createTestTempDirectory("rea-doctor-disk-permission-");
const docker = join(root, "docker");
const denied = join(root, "denied");
const target = join(denied, "docker");
const archive = join(denied, "runtime.tar.xz");
await program(docker, "exit 0");
await mkdir(target, { recursive: true });
await writeFile(archive, "unreadable archive");
const resources = new ArtifactResourceScope();
const factsAt = (directory: string, selectedArchive: string) =>
readDesktopBuildFacts({
environment: {
HOME: root,
PATH: "",
REA_DOCKER_COMMAND: docker,
REA_BUILD_COMPUTER_REA_ARCHIVE: selectedArchive,
},
platform: process.platform,
resources,
signal: new AbortController().signal,
run: async (_command, args) => {
const stdout = args[0] === "info" ? `${directory}\n` : "";
return {
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
};
},
clientIds: [],
registrations: async () => [],
});
await chmod(denied, 0);
try {
const facts = await factsAt(target, archive);
expect(facts.disk).toMatchObject({
path: target,
error: expect.stringContaining("EACCES"),
});
expect(facts.disk).not.toHaveProperty("freeBytes");
expect(facts.archive).toMatchObject({
path: archive,
status: "unknown",
detail: expect.stringContaining("EACCES"),
});
const missingArchive = join(root, "missing", "runtime.tar.xz");
const missing = await factsAt(
join(root, "missing", "docker"),
missingArchive,
);
expect(missing.disk).toMatchObject({
path: root,
freeBytes: expect.any(Number),
});
expect(missing.disk).not.toHaveProperty("error");
expect(missing.archive).toMatchObject({
path: missingArchive,
status: "missing",
});
} finally {
await chmod(denied, 0o700);
await resources.close();
}
},
);
it.skipIf(process.platform === "win32")(
"refuses a FIFO model configuration without waiting for a writer",
async () => {
+18 -7
View File
@@ -1,6 +1,6 @@
import { constants } from "node:fs";
import { access, stat, statfs } from "node:fs/promises";
import { dirname, isAbsolute, join } from "node:path";
import { dirname, isAbsolute } from "node:path";
import { z } from "zod";
@@ -31,6 +31,9 @@ import {
const DEFAULT_DOCKER_ROOT = "/var/lib/docker";
const CONFIG_BYTES = 1024 * 1024;
const missingPath = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
/** Inspect the same tar compression formats as the build's Python extractor without extracting files. */
const ARCHIVE_VERSION = String.raw`
import json, pathlib, sys, tarfile
@@ -235,7 +238,7 @@ const freeSpace = async (path: string): Promise<DesktopBuildFacts["disk"]> => {
return { path: candidate, freeBytes: fs.bavail * fs.bsize };
} catch (cause: unknown) {
const parent = dirname(candidate);
if (parent === candidate)
if (parent === candidate || !missingPath(cause))
return {
path,
error: cause instanceof Error ? cause.message : String(cause),
@@ -265,11 +268,19 @@ const archiveFact = async (
source === "cache"
? defaultBuildComputerArchive(input.environment, input.platform)
: (selected as string);
const file = await stat(path).then(
(entry) => entry.isFile(),
() => false,
);
if (!file) return { path, source, status: "missing" };
try {
if (!(await stat(path)).isFile())
return { path, source, status: "missing" };
} catch (cause: unknown) {
return missingPath(cause)
? { path, source, status: "missing" }
: {
path,
source,
status: "unknown",
detail: `REA could not inspect ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
};
}
if (source === "cache") return { path, source, status: "current" };
const python = await pythonForArchive();
if (python === undefined)
+1
View File
@@ -86,6 +86,7 @@ const formatSchema = z.enum([
"dfuse",
"esp-flash-image",
"fit",
"ntfs-mft",
"plist",
"javascript",
"source-map",
+56
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { MFT_INLINE_HEADER_LIMIT } from "./windows/ntfsMft.js";
import { jsonRecordSchema } from "./jsonRecord.js";
import { jsonValueSchema } from "./jsonValue.js";
@@ -299,6 +300,56 @@ export const hexRecordRegionMetadataSchema = z.strictObject({
last_line: offset,
});
const ntfsFileReferenceSchema = z.strictObject({
recordNumber: offset,
sequenceNumber: offset,
});
const ntfsRecordHeaderSchema = z.strictObject({
index: offset,
fileOffset: offset,
sequenceNumber: offset,
hardLinkCount: offset,
flags: z.strictObject({
raw: offset,
names: z.array(z.string()),
unknownMask: offset,
}),
inUse: z.boolean(),
directory: z.boolean(),
usedBytes: offset,
totalBytes: offset,
extentValid: z.boolean(),
baseRecordReference: ntfsFileReferenceSchema.nullable(),
declaredRecordNumber: offset.nullable(),
recordNumberMatchesSlot: z.boolean().nullable(),
logFileSequenceNumber: z.string().regex(/^(?:0|[1-9][0-9]*)$/u),
firstAttributeOffset: offset,
nextAttributeId: offset,
fixups: z.strictObject({
sequenceNumber: offset,
entries: offset,
verifiedSectors: offset,
coveredSectors: offset,
mismatchSector: offset.nullable(),
malformed: z.boolean(),
}),
});
/** NTFS $MFT record-header facts; attributes, names and the USN journal are later steps. */
export const ntfsMftMetadataSchema = z.strictObject({
kind: z.literal("ntfs-mft"),
record_bytes: offset,
record_count: offset,
in_use_record_count: offset,
directory_record_count: offset,
extension_record_count: offset,
fixup_mismatch_count: offset,
fixup_unverified_record_count: offset,
truncated_tail_bytes: offset,
record_headers: z.array(ntfsRecordHeaderSchema).max(MFT_INLINE_HEADER_LIMIT),
omitted_record_headers: offset,
});
/**
* U-Boot FIT root facts. Configuration references are declared names; a
* reference that names no image is reported as a limitation, not removed.
@@ -886,6 +937,7 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [
espImageSignatureBlockMetadataSchema,
uf2MetadataSchema,
uf2RegionMetadataSchema,
ntfsMftMetadataSchema,
dfuSeMetadataSchema,
dfuSeElementMetadataSchema,
espFlashImageMetadataSchema,
@@ -1036,6 +1088,10 @@ const declarationsByKind: {
notCompared:
"Its familyID and addresses are in its path, family_name is REA's label for the familyID, and its block counts and positions are layout; content comparison covers its bytes.",
},
"ntfs-mft": {
notCompared:
"Its fields come from the record headers in the file's own FILE records, which content comparison covers.",
},
dfuse: {
notCompared:
"Its fields come from the file's own prefix, target headers and suffix, which content comparison covers.",
+2
View File
@@ -103,6 +103,7 @@ export const ARTIFACT_FORMAT_IDS = [
"dfuse",
"esp-flash-image",
"fit",
"ntfs-mft",
"unknown",
] as const;
@@ -124,6 +125,7 @@ const artifactContentFormatSchema = artifactFormatSchema.extract([
"uf2",
"dfuse",
"fit",
"ntfs-mft",
"mach-o-universal",
"mach-o",
"elf",
+2 -1
View File
@@ -302,7 +302,8 @@ export type BinaryTarget =
| "esp-image"
| "uf2"
| "dfuse"
| "fit";
| "fit"
| "ntfs-mft";
})
| (BinaryTargetIdentity &
NonExecutableMetadata & {
+2 -2
View File
@@ -1,3 +1,4 @@
import { isPortableBundleName } from "../portableBundleName.js";
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
@@ -403,12 +404,11 @@ const screenProblem = (
/** Parse a task file and settle its check ids, or say what is wrong with it. */
export const parseDesktopTask = (
value: unknown,
isPortableName: (name: string) => boolean,
): Result<DesktopTask, string> => {
const parsed = desktopTaskSchema.safeParse(value);
if (!parsed.success) return err(describeValidationFailure(parsed.error));
const { name, prompt, checks, readers } = parsed.data;
if (!isPortableName(name) || name === "smoke")
if (!isPortableBundleName(name) || name === "smoke")
return err(
`name ${JSON.stringify(name)} must be a portable bundle name other than smoke: lowercase letters, digits and hyphens.`,
);
+20 -31
View File
@@ -13,8 +13,6 @@ import { elementText } from "./viewPointer.js";
import { redactSecretsInJson } from "./buildSecrets.js";
const portable = (name: string) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name);
it("redacts full check values before shortening descriptions without changing the verdict", () => {
const secret = "e-Plum7-Kite-Throwaway-42";
const actual = `${"x".repeat(180)}${secret}`;
@@ -53,10 +51,7 @@ const expectOutcome = (
};
const task = (checks: readonly unknown[]) =>
parseDesktopTask(
{ name: "edit-notes", prompt: "Edit my notes.", checks },
portable,
);
parseDesktopTask({ name: "edit-notes", prompt: "Edit my notes.", checks });
/** Task changes the parser refuses, each with part of its message. */
const REFUSALS: readonly (readonly [Record<string, unknown>, string])[] = [
@@ -1071,22 +1066,19 @@ describe("evaluateTaskChecks whole text", () => {
describe("parseDesktopTask", () => {
it("settles ids and keeps the prompt trimmed", () => {
const parsed = parseDesktopTask(
{
name: "add-milk",
prompt: " Add milk.\n",
checks: [
{ kind: "file_present", file: "Documents/todo.txt" },
{
id: "milk",
kind: "lines_present",
file: "Documents/todo.txt",
lines: ["milk"],
},
],
},
portable,
);
const parsed = parseDesktopTask({
name: "add-milk",
prompt: " Add milk.\n",
checks: [
{ kind: "file_present", file: "Documents/todo.txt" },
{
id: "milk",
kind: "lines_present",
file: "Documents/todo.txt",
lines: ["milk"],
},
],
});
expect(parsed).toMatchObject({
ok: true,
@@ -1098,15 +1090,12 @@ describe("parseDesktopTask", () => {
});
it.each(REFUSALS)("refuses %j", (change, message) => {
const parsed = parseDesktopTask(
{
name: "add-milk",
prompt: "Add milk.",
checks: [{ kind: "file_present", file: "a" }],
...change,
},
portable,
);
const parsed = parseDesktopTask({
name: "add-milk",
prompt: "Add milk.",
checks: [{ kind: "file_present", file: "a" }],
...change,
});
expect(parsed.ok).toBe(false);
if (!parsed.ok) expect(parsed.error).toContain(message);
+30 -7
View File
@@ -3,6 +3,7 @@ import { isNameLikeKey } from "./attributeRank.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js";
import { selectorOf } from "./viewSelector.js";
import { zipEntryAt } from "./zipView.js";
/** A file's views at its two ends. */
interface Ends {
@@ -10,6 +11,12 @@ interface Ends {
readonly final: JsonValue | null;
}
/** XML identifiers and field mirrors belong to one document, including within an archive. */
const documentAt = (view: JsonValue | null, pointer: string) => {
const entry = zipEntryAt(view, pointer);
return typeof entry === "object" ? entry : view;
};
/** The value of the name-like attribute a pointer's last step names its element by, as `label` for `[name=elementInformation][@name=label]`. */
const fieldKeyOf = (element: string) =>
selectorOf(
@@ -38,22 +45,35 @@ export const mirrorsOf = (
return element !== pointer &&
typeof before === "string" &&
typeof after === "string"
? [{ pointer, element, before, after }]
? [
{
pointer,
element,
before,
after,
document: documentAt(ends.final, pointer),
},
]
: [];
});
// The keys of the changed texts' elements, by what each was and became.
const keys = new Map<string, { pointer: string; key: string }[]>();
for (const { pointer, element, before, after } of texts) {
const keys = new Map<
string,
{ pointer: string; key: string; document: ReturnType<typeof documentAt> }[]
>();
for (const { pointer, element, before, after, document } of texts) {
const key = fieldKeyOf(element);
const alike = JSON.stringify([before, after]);
if (key === undefined) continue;
const group = keys.get(alike) ?? [];
group.push({ pointer, key });
group.push({ pointer, key, document });
keys.set(alike, group);
}
const mirrored = new Set(
texts.flatMap((mirror) => {
const sources = keys.get(JSON.stringify([mirror.before, mirror.after]));
const sources = keys
.get(JSON.stringify([mirror.before, mirror.after]))
?.filter(({ document }) => document === mirror.document);
const record = sources?.some(({ pointer }) => pointer !== mirror.pointer)
? resolvePointer(
ends.final,
@@ -136,13 +156,16 @@ export const idReferencesOf = (
) => {
const added = change.added.flatMap((pointer) => {
const element = resolvePointer(ends.final, pointer, "xml");
return isXmlElement(element) ? [{ pointer, element }] : [];
return isXmlElement(element)
? [{ pointer, element, document: documentAt(ends.final, pointer) }]
: [];
});
const mirrors = added.flatMap(({ pointer, element }) => {
const mirrors = added.flatMap(({ pointer, element, document }) => {
const [key = ""] = Object.keys(element.attributes);
return isIdReference(element) &&
added.some(
(record) =>
record.document === document &&
record.element !== element &&
!isIdReference(record.element) &&
record.element.attributes[key] === element.attributes[key],
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { evaluateTaskChecks } from "./appTaskChecks.js";
import {
draftOf,
passing,
@@ -776,3 +777,109 @@ describe("draftTaskFiles when a sibling lock changed", () => {
expect(lock?.suggested.length ?? 0).toBeGreaterThan(0);
});
});
it("keeps an added ID-only member when another XML archive entry independently adds the same ID", () => {
const archive = (added: boolean) => ({
entries: [
{
name: "records.xml",
size: 1,
sha256: added ? "end" : "seed",
format: "xml",
view: xml(
added
? '<doc><record id="6"><title>New record</title></record></doc>'
: "<doc/>",
),
view_error: null,
},
{
name: "other.xml",
size: 1,
sha256: added ? "end" : "seed",
format: "xml",
view: xml(added ? '<doc><entry id="6"/></doc>' : "<doc/>"),
view_error: null,
},
],
entry_count: 2,
truncated: false,
});
const file = "Documents/project.zip";
const [drafted] = draftOf({
[file]: statePath("document", "zip", archive(false), archive(true)),
});
expect(
drafted?.values.find(({ pointer }) => pointer.includes("[name=other.xml]"))
?.note,
).toBeUndefined();
const checks = (drafted?.suggested ?? []).filter(
(check) => "pointer" in check && check.pointer.includes("[name=other.xml]"),
);
expect(
evaluateTaskChecks(
checks.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([[file, { format: "zip", view: archive(false) }]]),
).map(({ passed }) => passed),
).toContain(false);
expect(
evaluateTaskChecks(
checks.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([[file, { format: "zip", view: archive(true) }]]),
).every(({ passed }) => passed),
).toBe(true);
});
it("keeps changed display text when its matching label belongs to another XML archive entry", () => {
const archive = (text: string) => ({
entries: [
{
name: "source.xml",
size: 1,
sha256: text,
format: "xml",
view: xml(
`<doc><record><field name="function">Independent function</field><field name="label">${text}</field></record></doc>`,
),
view_error: null,
},
{
name: "display.xml",
size: 1,
sha256: text,
format: "xml",
view: xml(
`<doc><record><display><text>${text}</text><info_name>label</info_name></display></record></doc>`,
),
view_error: null,
},
],
entry_count: 2,
truncated: false,
});
const file = "Documents/project.zip";
const [drafted] = draftOf({
[file]: statePath("document", "zip", archive("Old"), archive("New")),
});
expect(
drafted?.values.find(({ pointer }) =>
pointer.includes("[name=display.xml]"),
)?.note,
).toBeUndefined();
const checks = (drafted?.suggested ?? []).filter(
(check) =>
"pointer" in check && check.pointer.includes("[name=display.xml]"),
);
expect(
evaluateTaskChecks(
checks.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([[file, { format: "zip", view: archive("Old") }]]),
).map(({ passed }) => passed),
).toContain(false);
expect(
evaluateTaskChecks(
checks.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([[file, { format: "zip", view: archive("New") }]]),
).every(({ passed }) => passed),
).toBe(true);
});
+148
View File
@@ -0,0 +1,148 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { evaluateTaskChecks } from "./appTaskChecks.js";
import { draftOf, statePath } from "./appTaskDraft.fixture.js";
const FILE = "Documents/notes.db";
const table = (body: string, truncated = false) => ({
columns: ["id", "body"],
primary_key: ["id"],
rows: [[1, body]],
truncated,
});
const database = (tables: JsonValue, tables_truncated = false) => ({
tables,
tables_truncated,
});
const draft = (before: JsonValue, after: JsonValue) =>
draftOf({ [FILE]: statePath("document", "sqlite", before, after) })[0];
describe("SQLite draft row boundaries", () => {
it.each([
database({ notes: table("kept", true) }),
database({ notes: { error: "permission denied" } }),
database({}, true),
])(
"keeps unknown baseline rows separate from known empty tables: %j",
(before) => {
const after = database({ notes: table("kept"), other: table("new") });
const file = draft(before, after);
expect(file).toBeDefined();
expect(
file?.suggested.some(
(check) => "table" in check && check.table === "notes",
),
).toBe(false);
// The complete inventory can still establish that another table is new.
expect(
file?.suggested.some(
(check) => "table" in check && check.table === "other",
),
).toBe(before.tables_truncated === false);
},
);
it("retains checks for changes in fully read sibling tables", () => {
const before = database({
notes: table("kept", true),
other: table("old"),
});
const after = database({ notes: table("kept"), other: table("new") });
const checks = draft(before, after)?.suggested ?? [];
expect(checks).toEqual([
{
kind: "row_present",
file: FILE,
table: "other",
where: { id: 1, body: "new" },
},
]);
for (const [view, passed] of [
[before, false],
[after, true],
] as const)
expect(
evaluateTaskChecks(
checks.map((check) => ({ ...check, id: "changed" })),
new Map([[FILE, { format: "sqlite", view }]]),
).map((result) => result.passed),
).toEqual([passed]);
});
it("suggests only predicates that distinguish keyed rows after timestamp omission", () => {
const saved = (stamp: string) =>
database({
notes: {
columns: ["id", "body", "saved"],
primary_key: ["id"],
rows: [[1, "kept", stamp]],
truncated: false,
},
});
expect(
draft(saved("2026-11-04 09:00:00"), saved("2026-11-04 10:00:00"))
?.suggested ?? [],
).toEqual([]);
});
it("compares projected predicates against siblings when timestamp keys are omitted", () => {
const rows = (first: string) =>
database({
notes: {
columns: ["stamp", "body"],
primary_key: ["stamp"],
rows: [
["2026-11-04 09:00:00", first],
["2026-11-04 10:00:00", "new"],
],
truncated: false,
},
});
const before = rows("old");
const after = rows("new");
expect(draft(before, after)?.suggested ?? []).toEqual([]);
});
it("keeps a newly created SQLite file's presence check", () => {
const after = database({ notes: table("new") });
const file = draftOf({
[FILE]: statePath("document", "sqlite", null, after),
})[0];
expect(file?.suggested).toEqual([{ kind: "file_present", file: FILE }]);
});
it("compares keyed rows by column names through a table rebuild", () => {
const before = database({ notes: table("kept") });
const reordered = (body: string) =>
database({
notes: {
columns: ["body", "id"],
primary_key: ["id"],
rows: [[body, 1]],
truncated: false,
},
});
expect(draft(before, reordered("kept"))?.suggested ?? []).toEqual([]);
const after = reordered("edited");
const checks = draft(before, after)?.suggested ?? [];
expect(checks).toEqual([
{
kind: "row_present",
file: FILE,
table: "notes",
where: { body: "edited", id: 1 },
},
]);
for (const [view, passed] of [
[before, false],
[after, true],
] as const)
expect(
evaluateTaskChecks(
checks.map((check) => ({ ...check, id: "changed" })),
new Map([[FILE, { format: "sqlite", view }]]),
).map((result) => result.passed),
).toEqual([passed]);
});
});
+40 -18
View File
@@ -18,11 +18,14 @@ interface TableView {
readonly rows: readonly (readonly JsonValue[])[];
}
const tableViews = (version: Version): ReadonlyMap<string, TableView> => {
const tables = new Map<string, TableView>();
/** Keep unread tables distinct from absence in a complete table inventory. */
const tableViews = (version: Version) => {
const tables = new Map<string, TableView | undefined>();
const view = version.present ? version.view : null;
if (!isRecord(view) || !isRecord(view.tables)) return tables;
if (!isRecord(view) || !isRecord(view.tables))
return { tables, complete: false };
for (const [name, table] of Object.entries(view.tables)) {
tables.set(name, undefined);
if (!isRecord(table) || table.truncated !== false) continue;
const strings = (value: JsonValue | undefined) =>
Array.isArray(value)
@@ -34,7 +37,7 @@ const tableViews = (version: Version): ReadonlyMap<string, TableView> => {
rows: Array.isArray(table.rows) ? table.rows.filter(Array.isArray) : [],
});
}
return tables;
return { tables, complete: view.tables_truncated === false };
};
/** Column values of a row, without volatile values or the columns left out. */
@@ -110,16 +113,37 @@ export const rowSuggestions = (
): Suggestion[] => {
const before = tableViews(baseline);
const suggestions: Suggestion[] = [];
const push = (
kind: "row_present" | "row_absent",
table: string,
where: Record<string, JsonValue>,
) => {
if (Object.keys(where).length > 0)
suggestions.push({ kind, file, table, where });
};
for (const [name, table] of tableViews(final)) {
const old = before.get(name) ?? { ...table, rows: [] };
for (const [name, table] of tableViews(final).tables) {
if (table === undefined) continue;
const previousTable = before.tables.get(name);
if (
previousTable === undefined &&
(before.tables.has(name) || !before.complete)
)
continue;
const old = previousTable ?? { ...table, rows: [] };
// Judge the predicate after volatile values are omitted, using the same
// matching semantics as the evaluator rather than raw row positions.
const push = (
kind: "row_present" | "row_absent",
where: Record<string, JsonValue>,
previousRow?: readonly JsonValue[],
) => {
if (Object.keys(where).length === 0) return;
// A paired row is sufficient only while the predicate retains its
// complete key. Omitted timestamp keys can let siblings match too.
const previousRows =
previousRow !== undefined &&
old.key.every((column) => Object.hasOwn(where, column))
? [previousRow]
: old.rows;
if (
kind === "row_present"
? countTaskRows(old.columns, previousRows, where) === 0
: countTaskRows(table.columns, table.rows, where) === 0
)
suggestions.push({ kind, file, table: name, where });
};
const oldRows = keyedRows(old);
const newRows = keyedRows(table);
for (const [id, row] of newRows) {
@@ -127,13 +151,11 @@ export const rowSuggestions = (
if (previous === undefined)
push(
"row_present",
name,
rowWhere(table, row, (column) => !table.key.includes(column)),
);
else if (JSON.stringify(previous) !== JSON.stringify(row))
else
push(
"row_present",
name,
rowWhere(
table,
row,
@@ -142,13 +164,13 @@ export const rowSuggestions = (
JSON.stringify(row[table.columns.indexOf(column)]) !==
JSON.stringify(previous[old.columns.indexOf(column)]),
),
previous,
);
}
for (const [id, row] of oldRows)
if (!newRows.has(id))
push(
"row_absent",
name,
rowWhere(old, row, (column) => old.key.includes(column)),
);
suggestions.push(...unkeyedRowSuggestions(file, name, old, table));
@@ -157,7 +157,9 @@ describe("draftTaskFiles values", () => {
["removed", `${paragraph}/2`, "by_position"],
]);
});
});
describe("draftTaskFiles values budgets", () => {
it("lists at most 20 values and 8 KB a file and 24 KB a draft, saying when it left any out", () => {
const items = (count: number, value: (index: number) => string) =>
`<doc>${Array.from({ length: count }, (_, index) => `<p id="${String(index)}" v="${value(index)}"/>`).join("")}</doc>`;
@@ -194,6 +196,47 @@ describe("draftTaskFiles values", () => {
drafted[0]?.values.length ?? 0,
);
});
it.each([
{ files: 1, width: 1989, exact: true, cut: false },
{ files: 1, width: 1989, exact: false, cut: true },
{ files: 4, width: 1477, exact: true, cut: false },
{ files: 4, width: 1477, exact: false, cut: true },
])(
"includes serialized array delimiters in the values budget ($files files, exact: $exact)",
({ files, width, exact, cut }) => {
const keys = Array.from(
{ length: 4 },
(_, index) =>
`${String(index)}${"a".repeat(width - (exact && index === 0 ? 1 : 0))}`,
);
const drafted = draftOf(
Object.fromEntries(
Array.from({ length: files }, (_, index) => [
`settings-${String(index)}.json`,
statePath(
"application_state",
"json",
Object.fromEntries(keys.map((key) => [key, "x"])),
Object.fromEntries(keys.map((key) => [key, "y"])),
),
]),
),
);
const sizes = drafted.map(
(file) => new TextEncoder().encode(JSON.stringify(file.values)).length,
);
expect(sizes.every((size) => size <= 8192)).toBe(true);
expect(sizes.reduce((sum, size) => sum + size, 0)).toBeLessThanOrEqual(
24576,
);
expect(drafted.some((file) => file.values_cut)).toBe(cut);
if (exact)
expect(sizes.reduce((sum, size) => sum + size, 0)).toBe(
files === 1 ? 8192 : 24576,
);
},
);
});
it("preserves JSON objects whose keys resemble XML and archive views", () => {
+5 -4
View File
@@ -554,9 +554,9 @@ export const draftValues = (
.map((pointer) => entryOf(context, references, pointer, "removed")),
].toSorted((left, right) => rank(left) - rank(right));
const values: DraftValue[] = [];
let bytes = 0;
let bytes = 2; // The serialized values array's brackets.
for (const entry of entries) {
const size = byteLength(entry);
const size = byteLength(entry) + (values.length === 0 ? 0 : 1);
if (
values.length >= VALUE_LIMITS.entries ||
bytes + size > VALUE_LIMITS.fileBytes
@@ -606,11 +606,12 @@ export const withinDraftBudget = <
>(
files: readonly File[],
): File[] => {
let left = VALUE_LIMITS.draftBytes;
// Reserve every file's array brackets before assigning entry bytes in file order.
let left = VALUE_LIMITS.draftBytes - files.length * 2;
return files.map((file) => {
const kept: DraftValue[] = [];
for (const entry of file.values) {
const size = byteLength(entry);
const size = byteLength(entry) + (kept.length === 0 ? 0 : 1);
if (size > left) break;
kept.push(entry);
left -= size;
+3 -140
View File
@@ -492,146 +492,9 @@ async def _settled_views(url):
return views, True, False
`;
/** Where the verifier's evaluator begins. The task description is everything before it. */
const VERIFIER_EVALUATOR = "\nMISSING = object()\n";
/** The index helper this REA ships, and the one an older export wrote. The older one also accepts a leading zero. */
const CURRENT_INDEX = 'INDEX = re.compile(r"0|[1-9][0-9]*")';
const OLDER_INDEX = 'INDEX = re.compile(r"[0-9]+")';
/** A pointer segment the older index helper reads as an array index and this one does not, such as `01`. */
const LEADING_ZERO_SEGMENT = /^0\d+$/u;
/**
* The task a verifier states: the app, the checks and the settle timing,
* without the evaluator that runs them.
*/
export const taskVerifierDescription = (source: string): string | undefined => {
const at = source.indexOf(VERIFIER_EVALUATOR);
return at < 0 ? undefined : source.slice(0, at + 1);
};
/** The evaluator, from `MISSING` through `verify`, or undefined when that marker is absent. */
const verifierEvaluator = (source: string): string | undefined => {
const at = source.indexOf(VERIFIER_EVALUATOR);
return at < 0 ? undefined : source.slice(at);
};
/** Read one Python literal that `pythonLiteral` wrote, from `source` at `index`. */
const readPythonLiteral = (
source: string,
index: number,
): { readonly value: JsonValue; readonly index: number } | undefined => {
let cursor = index;
while (cursor < source.length && /\s/u.test(source[cursor] ?? ""))
cursor += 1;
const character = source[cursor];
if (source.startsWith("None", cursor))
return { value: null, index: cursor + 4 };
if (source.startsWith("True", cursor))
return { value: true, index: cursor + 4 };
if (source.startsWith("False", cursor))
return { value: false, index: cursor + 5 };
if (character === '"' || character === "'") {
let end = cursor + 1;
let escaped = false;
while (end < source.length) {
const next = source[end] ?? "";
if (escaped) escaped = false;
else if (next === "\\") escaped = true;
else if (next === character) break;
end += 1;
}
if (source[end] !== character) return undefined;
const token = source.slice(cursor, end + 1);
const value =
character === '"'
? (JSON.parse(token) as string)
: token.slice(1, -1).replaceAll("\\'", "'");
return { value, index: end + 1 };
}
if (character === "[") {
const items: JsonValue[] = [];
cursor += 1;
while (cursor < source.length) {
while (cursor < source.length && /\s/u.test(source[cursor] ?? ""))
cursor += 1;
if (source[cursor] === "]") return { value: items, index: cursor + 1 };
const item = readPythonLiteral(source, cursor);
if (item === undefined) return undefined;
items.push(item.value);
cursor = item.index;
while (cursor < source.length && /\s/u.test(source[cursor] ?? ""))
cursor += 1;
if (source[cursor] === ",") cursor += 1;
}
return undefined;
}
if (character === "{") {
const record: Record<string, JsonValue> = {};
cursor += 1;
while (cursor < source.length) {
while (cursor < source.length && /\s/u.test(source[cursor] ?? ""))
cursor += 1;
if (source[cursor] === "}") return { value: record, index: cursor + 1 };
const key = readPythonLiteral(source, cursor);
if (key === undefined || typeof key.value !== "string") return undefined;
cursor = key.index;
while (cursor < source.length && /\s/u.test(source[cursor] ?? ""))
cursor += 1;
if (source[cursor] !== ":") return undefined;
const item = readPythonLiteral(source, cursor + 1);
if (item === undefined) return undefined;
record[key.value] = item.value;
cursor = item.index;
while (cursor < source.length && /\s/u.test(source[cursor] ?? ""))
cursor += 1;
if (source[cursor] === ",") cursor += 1;
}
return undefined;
}
const number = /^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/u.exec(
source.slice(cursor),
);
if (number?.[0] === undefined) return undefined;
return { value: Number(number[0]), index: cursor + number[0].length };
};
/** Pointers of the checks a verifier states. A pointer inside a check's value is not one. */
const describedPointers = (description: string): readonly string[] => {
const at = description.indexOf("CHECKS = ");
if (at < 0) return [];
const parsed = readPythonLiteral(description, at + "CHECKS = ".length);
if (parsed === undefined || !Array.isArray(parsed.value)) return [];
return parsed.value.flatMap((check) =>
typeof check === "object" &&
check !== null &&
!Array.isArray(check) &&
typeof check.pointer === "string"
? [check.pointer]
: [],
);
};
/**
* Whether two verifiers grade the same task the same way. The description must
* match. The evaluator must be this REA's, or the older index helper alone
* when no pointer segment is a leading-zero number, which that helper would
* index and this one would not.
*/
export const sameTaskVerifier = (hosted: string, bundled: string): boolean => {
const expected = taskVerifierDescription(hosted);
const found = taskVerifierDescription(bundled);
if (expected === undefined || expected !== found) return false;
const hostedBody = verifierEvaluator(hosted);
const bundledBody = verifierEvaluator(bundled);
if (hostedBody === undefined || bundledBody === undefined) return false;
if (hostedBody === bundledBody) return true;
const indexed = describedPointers(expected).some((pointer) =>
pointer.split("/").some((segment) => LEADING_ZERO_SEGMENT.test(segment)),
);
return (
bundledBody === hostedBody.replace(CURRENT_INDEX, OLDER_INDEX) && !indexed
);
};
/** Match the current generated verifier exactly before witnessing its task. Older evaluators require a new export. */
export const sameTaskVerifier = (hosted: string, bundled: string): boolean =>
hosted.includes("\nMISSING = object()\n") && hosted === bundled;
/** The verifier artifact: a screen-judged task's judge, with the build's examples, or else reads of the app's state through its data/get once its files settle and the task's checks on them. */
export const renderTaskVerifier = (
@@ -18,120 +18,19 @@ const task: DesktopTask = {
};
describe("sameTaskVerifier", () => {
it("accepts an older evaluator of the same checks and rejects a different task", () => {
it("accepts the current generated verifier and rejects changed checks or evaluator code", () => {
const hosted = renderTaskVerifier(task, "notes");
const older = hosted.replace(
'INDEX = re.compile(r"0|[1-9][0-9]*")',
'INDEX = re.compile(r"[0-9]+")',
);
expect(older).not.toBe(hosted);
expect(sameTaskVerifier(hosted, older)).toBe(true);
expect(sameTaskVerifier(hosted, hosted.replace('"eggs"', '"milk"'))).toBe(
false,
);
expect(
sameTaskVerifier(hosted, older.replace("def _shown", "def _show")),
).toBe(false);
expect(
sameTaskVerifier(
hosted,
hosted.replace(/\nasync def verify[\s\S]*$/u, "\n"),
),
).toBe(false);
});
it("rejects the older index helper when a path segment has a leading zero", () => {
const indexed: DesktopTask = {
...task,
checks: [
{
id: "line",
kind: "value_absent",
file: "Documents/today.txt",
pointer: "/lines/01",
},
],
};
const hosted = renderTaskVerifier(indexed, "notes");
const older = hosted.replace(
'INDEX = re.compile(r"0|[1-9][0-9]*")',
'INDEX = re.compile(r"[0-9]+")',
);
expect(sameTaskVerifier(hosted, older)).toBe(false);
expect(sameTaskVerifier(hosted, hosted)).toBe(true);
});
it("accepts the older index helper when a leading zero is only in a file name or a URL", () => {
const named: DesktopTask = {
...task,
checks: [
{
id: "guide",
kind: "text_contains",
file: "Documents/01-notes.xml",
pointer: "/root",
value: "https://example.com/01-guide",
},
],
};
const hosted = renderTaskVerifier(named, "notes");
const older = hosted.replace(
'INDEX = re.compile(r"0|[1-9][0-9]*")',
'INDEX = re.compile(r"[0-9]+")',
);
expect(sameTaskVerifier(hosted, older)).toBe(true);
});
it("accepts the older index helper when a leading zero is only inside a check value", () => {
const stored: DesktopTask = {
...task,
checks: [
{
id: "settings",
kind: "value_equals",
file: "Documents/settings.json",
pointer: "/settings",
value: { pointer: "/lines/01" },
},
],
};
const hosted = renderTaskVerifier(stored, "notes");
const older = hosted.replace(
'INDEX = re.compile(r"0|[1-9][0-9]*")',
'INDEX = re.compile(r"[0-9]+")',
);
expect(sameTaskVerifier(hosted, older)).toBe(true);
});
it("rejects the older index helper when a brace inside an earlier check's text hides a leading-zero pointer", () => {
const indexed: DesktopTask = {
...task,
checks: [
{
id: "brace",
kind: "value_equals",
file: "Documents/today.txt",
pointer: "/lines/0",
value: "{",
},
{
id: "line",
kind: "value_absent",
file: "Documents/today.txt",
pointer: "/lines/01",
},
],
};
const hosted = renderTaskVerifier(indexed, "notes");
const older = hosted.replace(
'INDEX = re.compile(r"0|[1-9][0-9]*")',
'INDEX = re.compile(r"[0-9]+")',
);
expect(sameTaskVerifier(hosted, older)).toBe(false);
for (const bundled of [
hosted.replace('"eggs"', '"milk"'),
hosted.replace(
'INDEX = re.compile(r"0|[1-9][0-9]*")',
'INDEX = re.compile(r"[0-9]+")',
),
hosted.replace("def _shown", "def _show"),
hosted.replace(/\nasync def verify[\s\S]*$/u, "\n"),
])
expect(sameTaskVerifier(hosted, bundled)).toBe(false);
expect(sameTaskVerifier("not a verifier", "not a verifier")).toBe(false);
});
});
+7 -11
View File
@@ -8,7 +8,6 @@ import {
readerCommand,
} from "./appTaskReaders.js";
const portable = (name: string) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name);
const POSTER = "Documents/poster.xcf";
const LAYERS = {
@@ -27,16 +26,13 @@ const LAYER_CHECK = {
};
const parse = (change: Record<string, unknown>) =>
parseDesktopTask(
{
name: "rename-layer",
prompt: "In GIMP, rename the Headline layer to Summer Sale and save it.",
checks: [LAYER_CHECK],
readers: [LAYERS],
...change,
},
portable,
);
parseDesktopTask({
name: "rename-layer",
prompt: "In GIMP, rename the Headline layer to Summer Sale and save it.",
checks: [LAYER_CHECK],
readers: [LAYERS],
...change,
});
/** Task changes the parser refuses for its readers, each with part of its message. */
const REFUSALS: readonly (readonly [Record<string, unknown>, string])[] = [
+56 -40
View File
@@ -53,7 +53,6 @@ POLL_S = 0.05
DRAIN_S = 2.0
MAX_LINES = 5000
MAX_SAFE_INTEGER = 2**53 - 1
LINE_BREAK = re.compile(r"\r?\n")
SESSION = ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY")
NEVER = ("DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER", "XDG_RUNTIME_DIR")
FRESH = (("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"),
@@ -167,7 +166,14 @@ def _run(arguments: dict, source: str, work: str) -> dict:
return {"error": f"the reader ran past its {timeout} s{_tail(stderr)}"}
if process.returncode != 0:
return {"error": f"the reader exited {process.returncode}{_tail(stderr)}"}
lines = [line[len(MARKER):] for line in LINE_BREAK.split(printed.decode("utf-8", "replace")) if line.startswith(MARKER)]
# Unmarked startup text is not observation data. Decode only marked rows,
# without replacing malformed bytes with characters the reader never gave.
try:
marker = MARKER.encode("ascii")
lines = [line[len(marker):].removesuffix(b"\r").decode("utf-8")
for line in printed.split(b"\n") if line.startswith(marker)]
except UnicodeDecodeError:
return {"error": "the reader's marked output is not valid UTF-8"}
if not lines:
return {"error": f"the reader printed no line starting with {json.dumps(MARKER)}{_tail(stderr)}"}
return _view(arguments["output"], lines)
@@ -181,9 +187,9 @@ def main(arguments: dict) -> int:
except (FileNotFoundError, NotADirectoryError):
return _say({"absent": True})
except OSError as error:
return _say({"error": f"could not inspect the reader's file: {error.strerror or error}"})
return _say({"error": f"cannot inspect the reader's source: {error.strerror or error}"})
if not stat.S_ISREG(mode):
return _say({"absent": True})
return _say({"error": "the reader's source is not a regular file"})
# A remote caller owns this exact folder before starting the command, and
# removes it only after the command has settled.
lease = arguments.get("lease")
@@ -397,46 +403,56 @@ async def _reader_views(env_url, card):
if protocol.find_extension(card, EXEC) is None:
raise RuntimeError(f"the computer at {env_url} offers no {EXEC}, which runs the task's readers")
await _cleanup_readers(env_url, card)
views = {}
for reader in READERS:
token = uuid.uuid4().hex
lease = {"path": f"/tmp/rea-reader-{token}", "token": token}
arguments = json.loads("".join(reader["arguments"]))
arguments["lease"] = lease
encoded = json.dumps(arguments)
params = {"argv": ["python3", "-I", "-c", READER_RUNNER,
*(encoded[i:i + 8192] for i in range(0, len(encoded), 8192))],
"request_id": f"rea-reader-{token}",
"timeout_s": reader["timeout_s"] + RUNNER_SLACK_S}
task = _owned_task(protocol.invoke_extension(
env_url, card, EXEC, params, method="run", timeout=reader["timeout_s"] + 2 * RUNNER_SLACK_S))
_PENDING_READERS[token] = {"env_url": env_url, "lease": lease, "task": task,
"request_id": params["request_id"], "settled": False, "abandoned": False}
try:
answer = await asyncio.shield(task)
except BaseException as error:
_PENDING_READERS[token]["abandoned"] = True
error.add_note(f"Reader command {params['request_id']} and folder {lease['path']} remain owned for retry.")
raise
if not isinstance(answer, dict) or answer.get("timed_out"):
_PENDING_READERS[token]["abandoned"] = True
raise RuntimeError(f"Reader {params['request_id']} may still be running; retained {lease['path']}")
_PENDING_READERS[token]["settled"] = True
try:
view = _reader_answer(reader["id"], answer)
if view is not None:
views[reader["id"]] = view
finally:
views, absent = {}, []
try:
for reader in READERS:
token = uuid.uuid4().hex
lease = {"path": f"/tmp/rea-reader-{token}", "token": token}
arguments = json.loads("".join(reader["arguments"]))
arguments["lease"] = lease
encoded = json.dumps(arguments)
params = {"argv": ["python3", "-I", "-c", READER_RUNNER,
*(encoded[i:i + 8192] for i in range(0, len(encoded), 8192))],
"request_id": f"rea-reader-{token}",
"timeout_s": reader["timeout_s"] + RUNNER_SLACK_S}
task = _owned_task(protocol.invoke_extension(
env_url, card, EXEC, params, method="run", timeout=reader["timeout_s"] + 2 * RUNNER_SLACK_S))
_PENDING_READERS[token] = {"env_url": env_url, "lease": lease, "task": task,
"request_id": params["request_id"], "settled": False, "abandoned": False}
try:
answer = await asyncio.shield(task)
except BaseException as error:
_PENDING_READERS[token]["abandoned"] = True
error.add_note(f"Reader command {params['request_id']} and folder {lease['path']} remain owned for retry.")
raise
if not isinstance(answer, dict) or answer.get("timed_out"):
_PENDING_READERS[token]["abandoned"] = True
raise RuntimeError(f"Reader {params['request_id']} may still be running; retained {lease['path']}")
_PENDING_READERS[token]["settled"] = True
failure = None
try:
view = _reader_answer(reader["id"], answer)
if view is None:
absent.append(reader["id"])
else:
views[reader["id"]] = view
except BaseException as error:
failure = error
try:
await _cleanup_readers(env_url, card, token)
except asyncio.CancelledError as error:
except BaseException as error:
_PENDING_READERS[token]["abandoned"] = True
error.add_note(f"Reader cleanup remains owned for {lease['path']}; completed reader views: {json.dumps(views)}")
if failure is not None:
failure.add_note(f"Reader cleanup remains owned for {lease['path']}: {type(error).__name__}: {error}")
raise failure from error
error.add_note(f"Reader cleanup remains owned for {lease['path']}")
raise
except Exception as error:
_PENDING_READERS[token]["abandoned"] = True
raise RuntimeError(f"{error}; completed reader views: {json.dumps(views)}") from error
return views
if failure is not None:
raise failure
return views
except BaseException as error:
error.add_note(f"completed reader views: {json.dumps(views)}; completed reader absent: {json.dumps(absent)}")
raise
def evaluate_with_readers(checks: list, views: dict, readers: dict) -> list:
+7 -11
View File
@@ -10,23 +10,19 @@ import {
screenExamplesOf,
} from "./appTaskScreen.js";
const portable = (name: string) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name);
const SHOWN = {
id: "shown",
kind: "screen_judge",
question: "Does the calculator's display show the result 8.568?",
};
const parse = (change: Record<string, unknown>) =>
parseDesktopTask(
{
name: "tip-total",
prompt:
"In Calculator, work out 18% of 47.60 and leave the result showing.",
checks: [SHOWN],
...change,
},
portable,
);
parseDesktopTask({
name: "tip-total",
prompt:
"In Calculator, work out 18% of 47.60 and leave the result showing.",
checks: [SHOWN],
...change,
});
const EXAMPLES = { fail: "c2VlZA==", pass: "ZW5k" };
describe("screen_judge checks", () => {
+12
View File
@@ -188,6 +188,18 @@ describe("build secrets in escaped text", () => {
[{ handle: "xml", value: marked }],
),
).toBe('<p title="<secret:xml>">');
const xmlValue = 'e-a&b<c>d"-Fake';
const xmlSecrets = [{ handle: "xml", value: xmlValue }];
for (const encoded of [
"e-a&amp;b&lt;c>d&quot;-Fake",
"e-a&amp;b&lt;c&gt;d&quot;-Fake",
]) {
const document = `<p title="${encoded}">`;
expect(secretsIn(Buffer.from(document), xmlSecrets)).toEqual(["xml"]);
expect(redactSecrets(document, xmlSecrets)).toBe(
'<p title="<secret:xml>">',
);
}
expect(redactSecrets("text… unrelated", secrets)).toBe("text… unrelated");
const quoted = 'e-say"hi"\\now-Fake';
expect(
+5 -2
View File
@@ -74,10 +74,13 @@ const textSpellings = (value: string): readonly string[] => {
const form = new URLSearchParams([["value", value]])
.toString()
.slice("value=".length);
const escapedXml = xmlEscaped(value);
const xml = [
value,
xmlEscaped(value),
xmlEscaped(value).replaceAll('"', "&quot;"),
...[escapedXml, escapedXml.replaceAll(">", "&gt;")].flatMap((text) => [
text,
text.replaceAll('"', "&quot;"),
]),
];
return [
...new Set([
@@ -32,6 +32,7 @@ describe("the adaptive band", () => {
["3 of 3", "too_easy", [pass, pass, pass]],
["1 of 3", "undecided", [pass, miss, miss]],
["2 of 3", "undecided", [pass, pass, miss]],
["0 of 5", "too_hard", [miss, miss, miss, miss, miss]],
["1 of 5", "in_band", [pass, miss, miss, miss, miss]],
["3 of 5", "in_band", [pass, pass, miss, pass, miss]],
["4 of 5", "too_easy", [pass, pass, miss, pass, pass]],
+5 -1
View File
@@ -57,7 +57,11 @@ const counts = (solves: readonly SolveRecord[]) => {
export const bandOf = (solves: readonly SolveRecord[]): Band => {
const { done, passes } = counts(solves);
if (done >= ALL_SOLVES)
return passes <= MOST_BAND_PASSES ? "in_band" : "too_easy";
return passes === 0
? "too_hard"
: passes <= MOST_BAND_PASSES
? "in_band"
: "too_easy";
if (done >= FIRST_SOLVES && passes === 0) return "too_hard";
if (done >= FIRST_SOLVES && passes === done) return "too_easy";
return "undecided";
+1
View File
@@ -52,6 +52,7 @@ export const evidenceSubjectFormatSchema = z.enum([
"dfuse",
"esp-flash-image",
"fit",
"ntfs-mft",
]);
/** Format-owned architecture declarations shared by Evidence and persisted executions. */
@@ -137,7 +137,8 @@ describe("child-process options detection", () => {
["negative-zero", `spawn("tool", [], { env: -0 })`, false],
["bigint-zero", `spawn("tool", [], { env: 0n })`, false],
["zero-float", `spawn("tool", [], { env: 0.0 })`, false],
["nan", `spawn("tool", [], { env: NaN })`, true],
["nan", `spawn("tool", [], { env: NaN })`, false],
["shadowed-nan", `((NaN) => spawn("tool", [], { env: NaN }))({})`, true],
["empty-string", `spawn("tool", [], { env: "" })`, false],
["false", `spawn("tool", [], { env: false })`, false],
["empty-object", `spawn("tool", [], { env: {} })`, true],
@@ -81,7 +81,7 @@ export const collectJavaScriptSemanticChildProcesses = (
!rejectsOptionsShape(candidate, context, state),
);
const childProcessSpawns = candidates.map((candidate) =>
immutableSpawn(candidate, context),
immutableSpawn(candidate, context, state),
);
return {
childProcessSpawns,
@@ -146,6 +146,7 @@ const collectSpawns = (
const immutableSpawn = (
candidate: SpawnCandidate,
context: ChildSpawnContext,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticChildProcessSpawn => {
const { options, argvCount } = spawnArguments(candidate, context);
const command = dataEffectLiteralString(candidate.node.arguments[0]);
@@ -161,7 +162,7 @@ const immutableSpawn = (
projectedResultBindings: candidate.projectedResultBindings,
command,
argvCount,
environmentSupplied: environmentSupplied(options, context),
environmentSupplied: environmentSupplied(options, context, state),
stdioMode: stdioMode(options, candidate.method, context),
resolution: command === null ? "partial" : "complete",
};
@@ -443,11 +444,17 @@ const spawnArguments = (
const environmentSupplied = (
options: t.Node | undefined,
context: ChildSpawnContext,
state: JavaScriptSemanticAnalysisState,
): boolean => {
const lookup = staticObjectProperty(options, "env", context.isNullish);
if (lookup.status !== "explicit") return false;
const value = unwrapJavaScriptExpression(lookup.value).node;
if (context.isNullish(value)) return false;
if (
t.isIdentifier(value, { name: "NaN" }) &&
isUnshadowedGlobal(value, state, "NaN")
)
return false;
return staticJavaScriptTruthiness(value) !== false;
};
+1
View File
@@ -83,6 +83,7 @@ export const liveBinaryTargetSummaryVariants = [
"uf2",
"dfuse",
"fit",
"ntfs-mft",
]),
architecture: z.null(),
}),
+38
View File
@@ -0,0 +1,38 @@
import { z } from "zod";
import { normalizeHttpHostname } from "./httpHostname.js";
import { err, ok, type Result } from "./result.js";
/** Agentenv folder and local-id spelling, also used for authored task files. */
export const PORTABLE_BUNDLE_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
// A compose service name is one DNS label, whose wire limit is 63 octets.
export const PORTABLE_BUNDLE_NAME_MAX_LENGTH = 63;
export const PORTABLE_BUNDLE_NAME_CONSTRAINT = `a kebab-case label of at most ${String(PORTABLE_BUNDLE_NAME_MAX_LENGTH)} characters, excluding Windows device names, that remains unchanged as an HTTP service hostname`;
const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/u;
export type PortableBundleNameFailure = "format" | "reserved" | "hostname";
/** Admit the exact source name without normalizing it into another identity. */
export const parsePortableBundleName = (
name: string,
): Result<string, PortableBundleNameFailure> => {
if (
!PORTABLE_BUNDLE_NAME_PATTERN.test(name) ||
name.length > PORTABLE_BUNDLE_NAME_MAX_LENGTH
)
return err("format");
if (WINDOWS_RESERVED_NAME.test(name)) return err("reserved");
if (normalizeHttpHostname(name) !== name) return err("hostname");
return ok(name);
};
/** Boolean admission for callers that do not project a refusal. */
export const isPortableBundleName = (name: string): boolean =>
parsePortableBundleName(name).ok;
/** Lookup names share portable identity; authoring reservations are separate. */
export const portableBundleNameSchema = z
.string()
.regex(PORTABLE_BUNDLE_NAME_PATTERN)
.max(PORTABLE_BUNDLE_NAME_MAX_LENGTH)
.refine(isPortableBundleName, `Expected ${PORTABLE_BUNDLE_NAME_CONSTRAINT}`);
+3 -14
View File
@@ -157,7 +157,6 @@ const extractImports = (
ReferenceSourceRequireCall
>,
): void => {
let unresolvedRequireTarget = false;
traverseJavaScriptAst(ast.program, {
enter: (node) => {
if (
@@ -198,14 +197,8 @@ const extractImports = (
) {
const requireCall = requireCalls.get(node);
if (requireCall === undefined) return;
const target = requireCall.arguments?.[0];
if (target === undefined) return;
const literal = readExactJavaScriptLiteral(target);
if (!literal.found) {
unresolvedRequireTarget = true;
return;
}
if (typeof literal.value !== "string") return;
const specifier = exactStringModuleName(requireCall.arguments?.[0]);
if (specifier === undefined) return;
if (
requireCall.limitation !== undefined &&
!limitations.includes(requireCall.limitation)
@@ -214,7 +207,7 @@ const extractImports = (
const uncertainResolution = requireCall.resolutionBase === "unknown";
appendRelationship(relationships, limitations, {
fromPath: from_path,
to: literal.value,
to: specifier,
kind: "requires",
parseState: uncertainResolution ? "partial" : "parsed",
...(uncertainResolution ? { resolution: "unknown" } : {}),
@@ -228,10 +221,6 @@ const extractImports = (
}
},
});
if (unresolvedRequireTarget)
limitations.push(
`A CommonJS module target in ${from_path} could not be determined statically.`,
);
};
const parseWithBabel = (
+14
View File
@@ -1,3 +1,4 @@
import { posix } from "node:path";
import { err, ok, type Result } from "./result.js";
export interface ReferenceSourcePathLookup {
@@ -5,6 +6,8 @@ export interface ReferenceSourcePathLookup {
readonly has: (path: string) => boolean;
readonly resolve: (path: string) => string | undefined;
readonly resolveCandidates: (paths: readonly string[]) => string | undefined;
/** Resolve a path to the closest recorded parent identity. */
readonly resolveAncestor: (path: string) => string | undefined;
}
/**
@@ -32,6 +35,17 @@ export const createReferenceSourcePathLookup = (
resolveCandidates: (candidates) =>
candidates.find((path) => exact.has(path)) ??
candidates.map(equivalent).find((path) => path !== undefined),
resolveAncestor: (path) => {
for (
let candidate = path;
candidate !== "." && candidate !== "/";
candidate = posix.dirname(candidate)
) {
const found = resolve(candidate);
if (found !== undefined) return found;
}
return undefined;
},
};
};
+16 -17
View File
@@ -75,14 +75,9 @@ export const referenceSourceRequireCalls = (
!t.isNewExpression(node)
)
return;
const callee = unwrapJavaScriptExpression(node.callee).node;
if (
!t.isCallExpression(callee) &&
!t.isOptionalCallExpression(callee) &&
!hasIdentifierReceiver(callee)
)
return;
if (callReceiverIdentifier(node.callee) === undefined) return;
let fact = semanticRequireLoaderAt(node, index.bindings, factoryBindings);
const callee = unwrapJavaScriptExpression(node.callee).node;
if (
fact === "create-require" ||
((t.isMemberExpression(callee) ||
@@ -158,7 +153,12 @@ export const referenceSourceRequireCalls = (
});
},
});
if (candidates.some(({ call }) => hasMemberCallee(call)))
if (
candidates.some(
({ call }) =>
!t.isIdentifier(unwrapJavaScriptExpression(call.callee).node),
)
)
completeSemanticSteps(index.indexMemberMutationFactsSteps());
return new Map(
candidates.map(
@@ -169,7 +169,8 @@ export const referenceSourceRequireCalls = (
arguments: callArguments,
...(limitation === undefined ? {} : { limitation }),
resolutionBase:
hasMemberCallee(call) && hasPriorMemberMutation(index, call)
!t.isIdentifier(unwrapJavaScriptExpression(call.callee).node) &&
hasPriorMemberMutation(index, call)
? "unknown"
: resolutionBase,
},
@@ -219,17 +220,15 @@ const hasPriorMemberMutation = (
);
};
const hasMemberCallee = (call: ReferenceSourceRequireInvocation): boolean => {
const callee = unwrapJavaScriptExpression(call.callee).node;
return t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee);
};
const hasIdentifierReceiver = (callee: t.Node): boolean => {
let expression = callee;
const callReceiverIdentifier = (
callee: t.Node | null | undefined,
): t.Identifier | undefined => {
if (!t.isNode(callee)) return undefined;
let expression = unwrapJavaScriptExpression(callee).node;
while (
t.isMemberExpression(expression) ||
t.isOptionalMemberExpression(expression)
)
expression = unwrapJavaScriptExpression(expression.object).node;
return t.isIdentifier(expression);
return t.isIdentifier(expression) ? expression : undefined;
};
+478
View File
@@ -0,0 +1,478 @@
import { describe, expect, it } from "vitest";
import {
MFT_DEFAULT_RECORD_BYTES,
MFT_MAX_FILE_BYTES,
createMftDecoder,
parseMftImage,
} from "./ntfsMft.js";
interface RecordOptions {
readonly sequenceNumber?: number;
readonly hardLinkCount?: number;
readonly flags?: number;
readonly baseRecordReference?: bigint;
readonly recordBytes?: number;
/** Write a wrong trailer value into this sector, leaving the others correct. */
readonly corruptSector?: number;
/** Truncate the update sequence array to this many entries; 0 omits it. */
readonly usaEntries?: number;
readonly usaOffset?: number;
}
/** One FILE record with a zeroed body and fixups applied the way NTFS writes them. */
const recordOf = (options: RecordOptions = {}): Uint8Array => {
const recordBytes = options.recordBytes ?? MFT_DEFAULT_RECORD_BYTES;
const record = new Uint8Array(recordBytes);
const view = new DataView(record.buffer);
record.set(Buffer.from("FILE", "latin1"), 0);
const sequenceNumber = options.sequenceNumber ?? 1;
const sectors = recordBytes / 512;
const usaEntries = options.usaEntries ?? sectors + 1;
if (usaEntries > 0) {
const usaOffset = options.usaOffset ?? 48;
view.setUint16(4, usaOffset, true);
view.setUint16(6, usaEntries, true);
view.setUint16(usaOffset, sequenceNumber, true);
for (let sector = 0; sector < sectors; sector += 1) {
const trailer = sector * 512 + 510;
// A saved trailer is what the sector held before the fixup replaced it.
view.setUint16(usaOffset + 2 * (sector + 1), 0xa5a5, true);
view.setUint16(
trailer,
sector >= usaEntries - 1
? 0xa5a5
: sector === options.corruptSector
? 0x1234
: sequenceNumber,
true,
);
}
} else {
view.setUint16(4, 0, true);
view.setUint16(6, 0, true);
}
view.setUint16(16, sequenceNumber, true);
view.setUint16(18, options.hardLinkCount ?? 1, true);
const firstAttributeOffset =
Math.ceil((48 + Math.max(0, usaEntries) * 2) / 8) * 8;
view.setUint16(20, firstAttributeOffset, true);
view.setUint16(22, options.flags ?? 0x0001, true);
view.setUint32(24, firstAttributeOffset + 8, true);
view.setUint32(firstAttributeOffset, 0xffff_ffff, true);
view.setUint32(28, recordBytes, true);
view.setBigUint64(32, options.baseRecordReference ?? 0n, true);
view.setUint16(40, 0, true);
return record;
};
const streamOf = (...records: readonly Uint8Array[]): Uint8Array => {
const total = records.reduce((sum, record) => sum + record.length, 0);
const stream = new Uint8Array(total);
let offset = 0;
for (const record of records) {
stream.set(record, offset);
const view = new DataView(stream.buffer, offset, record.length);
if (view.getUint16(4, true) >= 48)
view.setUint32(44, offset / record.length, true);
offset += record.length;
}
return stream;
};
describe("MFT header facts", () => {
it("inventories a clean record's header and verified fixups", () => {
const parsed = parseMftImage(streamOf(recordOf({ sequenceNumber: 5 })));
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.metadata).toMatchObject({
kind: "ntfs-mft",
record_bytes: MFT_DEFAULT_RECORD_BYTES,
record_count: 1,
in_use_record_count: 1,
directory_record_count: 0,
extension_record_count: 0,
fixup_mismatch_count: 0,
fixup_unverified_record_count: 0,
truncated_tail_bytes: 0,
});
expect(parsed.value.records[0]).toMatchObject({
index: 0,
fileOffset: 0,
sequenceNumber: 5,
inUse: true,
directory: false,
baseRecordReference: null,
firstAttributeOffset: 56,
fixups: {
sequenceNumber: 5,
verifiedSectors: 2,
coveredSectors: 2,
mismatchSector: null,
malformed: false,
},
});
expect(parsed.value.limitations).toEqual([]);
});
it("identifies unrecognized flags without losing their source bits", () => {
const parsed = parseMftImage(recordOf({ flags: 0x8001 }));
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.metadata.record_headers[0]?.flags).toEqual({
raw: 0x8001,
names: ["in-use"],
unknownMask: 0x8000,
});
});
it.each([0, 49, 64, 72])(
"reports an invalid first attribute offset %i",
(offset) => {
const record = recordOf();
new DataView(record.buffer).setUint16(20, offset, true);
const parsed = parseMftImage(record);
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.records[0]?.extentValid).toBe(false);
expect(parsed.value.limitations.join(" ")).toContain("inconsistent");
},
);
it("reports a declared record number that contradicts its stream position", () => {
const bytes = streamOf(recordOf(), recordOf());
new DataView(bytes.buffer).setUint32(1024 + 44, 0, true);
const parsed = parseMftImage(bytes);
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.records[1]).toMatchObject({
index: 1,
declaredRecordNumber: 0,
recordNumberMatchesSlot: false,
});
expect(parsed.value.limitations.join(" ")).toContain(
"disagrees with their stream slot",
);
});
it("keeps the inline header window separate from the parsed record count", () => {
const parsed = parseMftImage(
streamOf(...Array.from({ length: 33 }, () => recordOf())),
);
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.metadata).toMatchObject({
record_count: 33,
omitted_record_headers: 1,
});
expect(parsed.value.metadata.record_headers).toHaveLength(32);
expect(parsed.value.records).toHaveLength(33);
expect(parsed.value.limitations).toEqual([]);
});
it("preserves a log sequence number above the safe integer range", () => {
const record = recordOf();
new DataView(record.buffer).setBigUint64(8, 9007199254740993n, true);
const parsed = parseMftImage(record);
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.records[0]?.logFileSequenceNumber).toBe(
"9007199254740993",
);
});
it("verifies the older FILE header without reading its fixup words as a record number", () => {
const oldRecord = recordOf({ usaOffset: 42 });
const newRecord = recordOf();
new DataView(newRecord.buffer).setUint32(44, 1, true);
const parsed = parseMftImage(streamOf(oldRecord, newRecord));
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.records).toMatchObject([
{
declaredRecordNumber: null,
fixups: { malformed: false, verifiedSectors: 2 },
},
{
declaredRecordNumber: 1,
fixups: { malformed: false, verifiedSectors: 2 },
},
]);
expect(parsed.value.limitations).toEqual([]);
});
});
describe("MFT fixup coverage", () => {
it.each([0, 0xffff])(
"leaves reserved USA sequence %i unverified",
(sequenceNumber) => {
const parsed = parseMftImage(recordOf({ sequenceNumber }));
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.records[0]?.fixups).toMatchObject({
sequenceNumber,
verifiedSectors: 0,
malformed: true,
});
expect(parsed.value.metadata.fixup_unverified_record_count).toBe(1);
expect(parsed.value.limitations.join(" ")).toContain(
"invalid or incomplete",
);
},
);
it("keeps a record whose sector trailer is not the sequence number, and reports it", () => {
const parsed = parseMftImage(
streamOf(recordOf(), recordOf({ sequenceNumber: 9, corruptSector: 1 })),
);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.records[1]?.fixups).toMatchObject({
sequenceNumber: 9,
verifiedSectors: 1,
mismatchSector: 1,
});
expect(parsed.value.metadata.fixup_mismatch_count).toBe(1);
expect(parsed.value.limitations.join(" ")).toMatch(
/1 record\(s\) hold a sector trailer/u,
);
});
it("treats a missing update sequence array as unverified rather than clean", () => {
const parsed = parseMftImage(streamOf(recordOf({ usaEntries: 0 })));
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.records[0]?.fixups).toMatchObject({
malformed: true,
mismatchSector: null,
coveredSectors: 0,
});
expect(parsed.value.metadata.fixup_mismatch_count).toBe(0);
expect(parsed.value.metadata.fixup_unverified_record_count).toBe(1);
expect(parsed.value.limitations.join(" ")).toMatch(
/invalid or incomplete update sequence array/u,
);
});
it.each([
[48, 4],
[49, 3],
[508, 3],
])(
"rejects a malformed update sequence array at %i with %i entries",
(offset, count) => {
const bytes = recordOf();
const view = new DataView(bytes.buffer);
view.setUint16(4, offset, true);
view.setUint16(6, count, true);
const parsed = parseMftImage(bytes);
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.records[0]?.fixups).toMatchObject({
malformed: true,
verifiedSectors: 0,
});
expect(parsed.value.metadata.fixup_unverified_record_count).toBe(1);
},
);
it("counts uncovered sectors independently of a mismatched trailer", () => {
const parsed = parseMftImage(
recordOf({ recordBytes: 4096, usaEntries: 3, corruptSector: 0 }),
);
if (!parsed.ok) throw new Error(parsed.error.message);
expect(parsed.value.metadata).toMatchObject({
fixup_mismatch_count: 1,
fixup_unverified_record_count: 1,
});
expect(parsed.value.limitations.join(" ")).toContain(
"invalid or incomplete",
);
});
it("reports an array that covers fewer sectors than the record has", () => {
// A 4 KiB record holds eight sectors; a three-entry array leaves five unverified.
const parsed = parseMftImage(
streamOf(recordOf({ recordBytes: 4096, usaEntries: 3 })),
);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.records[0]?.fixups).toMatchObject({
coveredSectors: 2,
verifiedSectors: 2,
mismatchSector: null,
malformed: false,
});
expect(parsed.value.metadata.fixup_unverified_record_count).toBe(1);
});
});
describe("MFT record slots", () => {
it("distinguishes extension records from base records", () => {
const parsed = parseMftImage(
streamOf(
recordOf(),
recordOf({
flags: 0x0005,
baseRecordReference: 0xabcd_fedc_ba98_7654n,
}),
),
);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.records[1]).toMatchObject({
baseRecordReference: {
recordNumber: 0xfedc_ba98_7654,
sequenceNumber: 0xabcd,
},
flags: { raw: 0x0005, names: ["in-use", "system"] },
});
expect(parsed.value.metadata.extension_record_count).toBe(1);
});
it("names directory records without losing the in-use flag", () => {
const parsed = parseMftImage(streamOf(recordOf({ flags: 0x0003 })));
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.records[0]).toMatchObject({
directory: true,
inUse: true,
flags: { names: ["in-use", "directory"] },
});
expect(parsed.value.metadata.directory_record_count).toBe(1);
});
it("skips malformed and sparse slots without renumbering valid records", () => {
const stream = streamOf(
recordOf(),
recordOf(),
new Uint8Array(MFT_DEFAULT_RECORD_BYTES),
recordOf(),
);
stream.set(Buffer.from("BAAD", "latin1"), MFT_DEFAULT_RECORD_BYTES);
const parsed = parseMftImage(stream);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.metadata.record_count).toBe(2);
expect(
parsed.value.records.map(({ index, fileOffset }) => [index, fileOffset]),
).toEqual([
[0, 0],
[3, 3 * MFT_DEFAULT_RECORD_BYTES],
]);
expect(parsed.value.limitations).toEqual([
"record at 1024 does not begin with the FILE signature; 2 slot(s) without a FILE signature were found",
]);
});
it("keeps a trailing partial record out of the inventory", () => {
const stream = new Uint8Array(1024 + 300);
stream.set(recordOf(), 0);
const parsed = parseMftImage(stream);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.metadata.record_count).toBe(1);
expect(parsed.value.metadata.truncated_tail_bytes).toBe(300);
expect(parsed.value.limitations.join(" ")).toMatch(
/300 trailing byte\(s\)/u,
);
});
it("falls back to the default record size when record 0 declares none", () => {
const record = recordOf();
new DataView(record.buffer).setUint32(28, 0, true);
const parsed = parseMftImage(record);
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.recordBytes).toBe(MFT_DEFAULT_RECORD_BYTES);
expect(parsed.value.limitations.join(" ")).toMatch(
/not a supported power of two/u,
);
});
it("reads a 4 KiB record at its declared size", () => {
const parsed = parseMftImage(streamOf(recordOf({ recordBytes: 4096 })));
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.value.recordBytes).toBe(4096);
expect(parsed.value.metadata.record_count).toBe(1);
});
});
describe("parseMftImage refusals and limits", () => {
it("refuses a file shorter than one record header", () => {
const parsed = parseMftImage(new Uint8Array(32));
expect(parsed.ok).toBe(false);
if (parsed.ok) return;
expect(parsed.error.message).toMatch(
/shorter than one 42-byte record header/u,
);
});
it("refuses bytes that do not start with the FILE signature", () => {
const parsed = parseMftImage(Buffer.alloc(2048, 0x41));
expect(parsed.ok).toBe(false);
if (parsed.ok) return;
expect(parsed.error.message).toMatch(
/does not begin with the FILE signature/u,
);
});
it("refuses a file above the fixed ceiling", () => {
const decoder = createMftDecoder(MFT_MAX_FILE_BYTES + 1);
expect(decoder.ok).toBe(false);
if (decoder.ok) return;
expect(decoder.error).toMatchObject({
kind: "limit",
boundary: "file-size",
});
});
it("refuses streams that differ from the admitted byte count", () => {
const stream = recordOf();
const short = createMftDecoder(stream.length + 1);
if (!short.ok) throw new Error(short.error.message);
expect(short.value.write(stream).ok).toBe(true);
expect(short.value.finish()).toMatchObject({
ok: false,
error: {
kind: "format",
message: "stream ended before the admitted file length",
},
});
const long = createMftDecoder(stream.length - 1);
if (!long.ok) throw new Error(long.error.message);
expect(long.value.write(stream)).toMatchObject({
ok: false,
error: {
kind: "format",
message: "received more bytes than the admitted file length",
},
});
});
it("returns the same inventory without retaining all the decoded records", () => {
const bytes = streamOf(...Array.from({ length: 33 }, () => recordOf()));
const decoder = createMftDecoder(bytes.length);
const parsed = parseMftImage(bytes);
if (!decoder.ok || !parsed.ok) throw new Error("invalid fixture");
expect(decoder.value.write(bytes).ok).toBe(true);
const inventory = decoder.value.finish();
if (!inventory.ok) throw new Error(inventory.error.message);
expect(inventory.value).not.toHaveProperty("records");
expect(inventory.value.metadata).toEqual(parsed.value.metadata);
expect(inventory.value.limitations).toEqual(parsed.value.limitations);
});
it("decodes the same stream through the chunked decoder", () => {
const stream = streamOf(recordOf(), recordOf({ flags: 0x0003 }));
const decoder = createMftDecoder(stream.length);
expect(decoder.ok).toBe(true);
if (!decoder.ok) return;
// Feed one byte past a record boundary so a chunk never aligns with a record.
for (const chunk of [stream.subarray(0, 1025), stream.subarray(1025)])
expect(decoder.value.write(chunk).ok).toBe(true);
const image = decoder.value.finish();
expect(image.ok).toBe(true);
if (!image.ok) return;
expect(image.value.metadata.record_count).toBe(2);
expect(image.value.metadata.directory_record_count).toBe(1);
});
});
+512
View File
@@ -0,0 +1,512 @@
import { err, ok, type Result } from "../result.js";
import type {
RegionDecodeFailure,
RegionDecoder,
} from "../firmware/regionDecoder.js";
/** An NTFS FILE record begins with this signature. */
const MFT_FILE_RECORD_MAGIC = "FILE";
const MFT_FILE_RECORD_MAGIC_BYTES = 4;
/** The shortest header worth reading: a FILE record header ends at `nextAttributeId`. */
const NTFS_MFT_MIN_RECORD_BYTES = 42;
const hasMftFileRecordSignature = (prefix: Uint8Array): boolean =>
prefix.length >= MFT_FILE_RECORD_MAGIC_BYTES &&
text(prefix.subarray(0, MFT_FILE_RECORD_MAGIC_BYTES)) ===
MFT_FILE_RECORD_MAGIC;
/** A record's declared size is a power of two from 512 upward; 1024 is NTFS's default. */
export const MFT_DEFAULT_RECORD_BYTES = 1024;
const MFT_MIN_RECORD_BYTES = 512;
const MFT_MAX_RECORD_BYTES = 65536;
/** An update sequence array holds at least the sequence number and one fixup word. */
const USA_MIN_ENTRIES = 2;
/** NTFS fixes up one 512-byte sector at a time. */
const FIXUP_SECTOR_BYTES = 512;
/**
* Fixed whole-file ceiling. Records are inventoried from their headers only;
* attributes and their payloads are not decoded, so this is deliberately
* smaller than a volume's MFT can be.
*/
export const MFT_MAX_FILE_BYTES = 512 * 1024 * 1024;
/** Limit the inline header sample independently of full stream coverage. */
export const MFT_INLINE_HEADER_LIMIT = 32;
/** FILE record header fields; offsets are from the record start. */
const RECORD_HEADER = {
updateSequenceOffset: 4,
updateSequenceCount: 6,
logFileSequenceNumber: 8,
sequenceNumber: 16,
hardLinkCount: 18,
firstAttributeOffset: 20,
flags: 22,
usedBytes: 24,
totalBytes: 28,
baseRecordReference: 32,
nextAttributeId: 40,
recordNumber: 44,
} as const;
const RECORD_HEADER_WITH_NUMBER_BYTES = 48;
const FILE_RECORD_IN_USE = 0x0001;
const FILE_RECORD_IS_DIRECTORY = 0x0002;
const FILE_RECORD_NAMES = new Map<number, string>([
[FILE_RECORD_IN_USE, "in-use"],
[FILE_RECORD_IS_DIRECTORY, "directory"],
[0x0004, "system"],
[0x0008, "view-index"],
]);
export interface MftRecordFixups {
/** The update sequence number the array's first entry holds, or 0 when absent. */
readonly sequenceNumber: number;
readonly entries: number;
/** Sectors whose trailer held the sequence number before a mismatch. */
readonly verifiedSectors: number;
/** Sectors the array covers; fewer than the record's sectors leaves a tail unverified. */
readonly coveredSectors: number;
/** The first sector whose trailer did not hold the sequence number, if any. */
readonly mismatchSector: number | null;
/** The array itself is missing, misplaced or too short to cover one sector. */
readonly malformed: boolean;
}
export interface MftFileReference {
readonly recordNumber: number;
readonly sequenceNumber: number;
}
const decodeMftFileReference = (reference: bigint): MftFileReference => ({
recordNumber: Number(reference & 0xffff_ffff_ffffn),
sequenceNumber: Number(reference >> 48n),
});
export interface MftRecord {
/** Zero-based ordinal of this record in the stream. */
readonly index: number;
/** File offset where the record starts. */
readonly fileOffset: number;
readonly sequenceNumber: number;
/** Hard link count as recorded; a zero count marks a record with no names. */
readonly hardLinkCount: number;
readonly flags: {
readonly raw: number;
readonly names: readonly string[];
readonly unknownMask: number;
};
readonly inUse: boolean;
readonly directory: boolean;
/** Used and allocated byte counts as declared by the FILE record. */
readonly usedBytes: number;
readonly totalBytes: number;
readonly extentValid: boolean;
/** The base record this is an extension of, or `null` for a base record. */
readonly baseRecordReference: MftFileReference | null;
/** The record number the header declares; `null` when the header predates the field. */
readonly declaredRecordNumber: number | null;
readonly recordNumberMatchesSlot: boolean | null;
/** `$LogFile` sequence number as recorded; no log is read. */
readonly logFileSequenceNumber: string;
/** Declared offset of the first attribute; no attribute decoding follows yet. */
readonly firstAttributeOffset: number;
/** Declared id of the next attribute; no attribute decoding follows yet. */
readonly nextAttributeId: number;
readonly fixups: MftRecordFixups;
}
export interface MftInventory {
readonly metadata: MftMetadata;
/** The record size the stream declared, or the fixed default when it did not. */
readonly recordBytes: number;
readonly limitations: readonly string[];
}
export interface MftImage extends MftInventory {
readonly records: readonly MftRecord[];
}
export interface MftMetadata {
readonly kind: "ntfs-mft";
readonly record_bytes: number;
readonly record_count: number;
readonly in_use_record_count: number;
readonly directory_record_count: number;
readonly extension_record_count: number;
readonly fixup_mismatch_count: number;
readonly fixup_unverified_record_count: number;
readonly truncated_tail_bytes: number;
readonly record_headers: readonly MftRecord[];
readonly omitted_record_headers: number;
}
const text = (ascii: Uint8Array): string =>
Buffer.from(ascii).toString("latin1");
const failure = (
message: string,
boundary?: RegionDecodeFailure["boundary"],
): RegionDecodeFailure => ({
kind: "format",
message,
...(boundary === undefined ? {} : { boundary }),
});
const limit = (
message: string,
boundary?: RegionDecodeFailure["boundary"],
): RegionDecodeFailure => ({
kind: "limit",
message,
...(boundary === undefined ? {} : { boundary }),
});
const parseRecordFlags = (raw: number): MftRecord["flags"] => {
const names: string[] = [];
let unknownMask = raw;
for (const [bit, name] of FILE_RECORD_NAMES) {
if ((raw & bit) !== 0) names.push(name);
unknownMask &= ~bit;
}
return { raw, names, unknownMask };
};
const isRecordSize = (bytes: number): boolean =>
bytes >= MFT_MIN_RECORD_BYTES &&
bytes <= MFT_MAX_RECORD_BYTES &&
(bytes & (bytes - 1)) === 0;
const updateSequenceArrayFits = (
offset: number,
entries: number,
sectors: number,
): boolean =>
entries >= USA_MIN_ENTRIES &&
entries <= sectors + 1 &&
offset >= NTFS_MFT_MIN_RECORD_BYTES &&
offset % 2 === 0 &&
offset + entries * 2 <= FIXUP_SECTOR_BYTES - 2;
/** Recognize a FILE header without requiring its trailers or attributes to verify. */
export const hasMftFileRecordHeader = (prefix: Uint8Array): boolean => {
if (
prefix.length < NTFS_MFT_MIN_RECORD_BYTES ||
!hasMftFileRecordSignature(prefix)
)
return false;
const view = new DataView(
prefix.buffer,
prefix.byteOffset,
prefix.byteLength,
);
return (
isRecordSize(view.getUint32(RECORD_HEADER.totalBytes, true)) ||
updateSequenceArrayFits(
view.getUint16(RECORD_HEADER.updateSequenceOffset, true),
view.getUint16(RECORD_HEADER.updateSequenceCount, true),
MFT_DEFAULT_RECORD_BYTES / FIXUP_SECTOR_BYTES,
)
);
};
/**
* Parse FILE record headers and verify their update-sequence fixups.
*
* Only the record structure is established: attributes, their names, the
* filenames and the USN journal are left to later steps, so no path, timestamp
* or file identity beyond the record itself is claimed. A record whose fixup
* does not match keeps its header facts, because the stream still declares it,
* and the mismatch is reported on the record and counted in the metadata.
*/
export const parseMftImage = (
bytes: Uint8Array,
): Result<MftImage, RegionDecodeFailure> => {
const records: MftRecord[] = [];
const inventory = scanMft(bytes, records);
return inventory.ok ? ok({ ...inventory.value, records }) : inventory;
};
const scanMft = (
bytes: Uint8Array,
retainedRecords?: MftRecord[],
): Result<MftInventory, RegionDecodeFailure> => {
if (bytes.length < NTFS_MFT_MIN_RECORD_BYTES)
return err(
failure(
`file is ${String(bytes.length)} bytes, shorter than one ${String(NTFS_MFT_MIN_RECORD_BYTES)}-byte record header`,
),
);
if (!hasMftFileRecordSignature(bytes))
return err(failure("record 0 does not begin with the FILE signature"));
const limitations: string[] = [];
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const declaredRecordBytes = header.getUint32(RECORD_HEADER.totalBytes, true);
const recordBytes = isRecordSize(declaredRecordBytes)
? declaredRecordBytes
: MFT_DEFAULT_RECORD_BYTES;
if (!isRecordSize(declaredRecordBytes))
limitations.push(
`record 0 declares a record size of ${String(declaredRecordBytes)} bytes, which is not a supported power of two from ${String(MFT_MIN_RECORD_BYTES)} to ${String(MFT_MAX_RECORD_BYTES)}; records were read at the ${String(MFT_DEFAULT_RECORD_BYTES)}-byte default`,
);
const recordHeaders: MftRecord[] = [];
let recordCount = 0;
let inUseCount = 0;
let directoryCount = 0;
let extensionCount = 0;
let mismatchCount = 0;
let unverifiedCount = 0;
let invalidSlots = 0;
let invalidExtents = 0;
let inconsistentRecordNumbers = 0;
let firstInvalidExtentOffset: number | undefined;
let firstInvalidOffset: number | undefined;
for (
let offset = 0;
offset + recordBytes <= bytes.length;
offset += recordBytes
) {
if (
!hasMftFileRecordSignature(
bytes.subarray(offset, offset + MFT_FILE_RECORD_MAGIC_BYTES),
)
) {
invalidSlots += 1;
firstInvalidOffset ??= offset;
if (!isRecordSize(declaredRecordBytes)) break;
continue;
}
const record = readRecord(bytes, offset, offset / recordBytes, recordBytes);
retainedRecords?.push(record);
if (recordHeaders.length < MFT_INLINE_HEADER_LIMIT)
recordHeaders.push(record);
recordCount += 1;
if (record.inUse) inUseCount += 1;
if (record.directory) directoryCount += 1;
if (record.baseRecordReference !== null) extensionCount += 1;
if (record.fixups.mismatchSector !== null) mismatchCount += 1;
if (
record.fixups.malformed ||
record.fixups.coveredSectors < recordBytes / FIXUP_SECTOR_BYTES
)
unverifiedCount += 1;
if (record.recordNumberMatchesSlot === false)
inconsistentRecordNumbers += 1;
if (!record.extentValid) {
invalidExtents += 1;
firstInvalidExtentOffset ??= offset;
}
}
if (firstInvalidOffset !== undefined)
limitations.push(
`record at ${String(firstInvalidOffset)} does not begin with the FILE signature; ${String(invalidSlots)} slot(s) without a FILE signature were found`,
);
if (firstInvalidExtentOffset !== undefined)
limitations.push(
`${String(invalidExtents)} FILE record(s) declare inconsistent record extents, beginning at offset ${String(firstInvalidExtentOffset)}`,
);
if (inconsistentRecordNumbers !== 0)
limitations.push(
`${String(inconsistentRecordNumbers)} FILE record(s) declare a record number that disagrees with their stream slot`,
);
const truncatedTailBytes = bytes.length % recordBytes;
if (truncatedTailBytes !== 0)
limitations.push(
`${String(truncatedTailBytes)} trailing byte(s) do not fill a ${String(recordBytes)}-byte record and were not parsed`,
);
if (mismatchCount !== 0)
limitations.push(
`${String(mismatchCount)} record(s) hold a sector trailer that is not the update sequence number; their attributes were not read and no later step should trust them`,
);
if (unverifiedCount !== 0)
limitations.push(
`${String(unverifiedCount)} record(s) carry an invalid or incomplete update sequence array; their sector trailers were not fully verified`,
);
const metadata: MftMetadata = {
kind: "ntfs-mft",
record_bytes: recordBytes,
record_count: recordCount,
in_use_record_count: inUseCount,
directory_record_count: directoryCount,
extension_record_count: extensionCount,
fixup_mismatch_count: mismatchCount,
fixup_unverified_record_count: unverifiedCount,
truncated_tail_bytes: truncatedTailBytes,
record_headers: recordHeaders,
omitted_record_headers: recordCount - recordHeaders.length,
};
return ok({ metadata, recordBytes, limitations });
};
const readRecord = (
bytes: Uint8Array,
fileOffset: number,
index: number,
recordBytes: number,
): MftRecord => {
const record = bytes.subarray(fileOffset, fileOffset + recordBytes);
const view = new DataView(
record.buffer,
record.byteOffset,
record.byteLength,
);
const flags = view.getUint16(RECORD_HEADER.flags, true);
const baseRecordReference = view.getBigUint64(
RECORD_HEADER.baseRecordReference,
true,
);
const usaOffset = view.getUint16(RECORD_HEADER.updateSequenceOffset, true);
const fixups = verifyFixups(record, view, usaOffset);
const usedBytes = view.getUint32(RECORD_HEADER.usedBytes, true);
const totalBytes = view.getUint32(RECORD_HEADER.totalBytes, true);
const firstAttributeOffset = view.getUint16(
RECORD_HEADER.firstAttributeOffset,
true,
);
const declaredRecordNumber =
!fixups.malformed && usaOffset >= RECORD_HEADER_WITH_NUMBER_BYTES
? view.getUint32(RECORD_HEADER.recordNumber, true)
: null;
return {
index,
fileOffset,
sequenceNumber: view.getUint16(RECORD_HEADER.sequenceNumber, true),
hardLinkCount: view.getUint16(RECORD_HEADER.hardLinkCount, true),
flags: parseRecordFlags(flags),
inUse: (flags & FILE_RECORD_IN_USE) !== 0,
directory: (flags & FILE_RECORD_IS_DIRECTORY) !== 0,
usedBytes,
totalBytes,
extentValid:
totalBytes === recordBytes &&
usedBytes >= NTFS_MFT_MIN_RECORD_BYTES &&
usedBytes % 8 === 0 &&
usedBytes <= totalBytes &&
firstAttributeOffset % 8 === 0 &&
firstAttributeOffset >= NTFS_MFT_MIN_RECORD_BYTES &&
firstAttributeOffset + 4 <= usedBytes &&
(fixups.malformed ||
firstAttributeOffset >= usaOffset + fixups.entries * 2),
baseRecordReference:
baseRecordReference === 0n
? null
: decodeMftFileReference(baseRecordReference),
declaredRecordNumber,
recordNumberMatchesSlot:
declaredRecordNumber === null ? null : declaredRecordNumber === index,
logFileSequenceNumber: view
.getBigUint64(RECORD_HEADER.logFileSequenceNumber, true)
.toString(),
firstAttributeOffset,
nextAttributeId: view.getUint16(RECORD_HEADER.nextAttributeId, true),
fixups,
};
};
/**
* Each sector's last two bytes are replaced on disk by the update sequence
* number; the array's first entry is that number and the rest are the saved
* trailer words. A sector whose trailer is not the sequence number was not
* cleanly written, so the record's attributes cannot be trusted.
*/
const verifyFixups = (
record: Uint8Array,
view: DataView,
usaOffset: number,
): MftRecordFixups => {
const usaCount = view.getUint16(RECORD_HEADER.updateSequenceCount, true);
const sectors = Math.floor(record.length / FIXUP_SECTOR_BYTES);
// Entry 0 holds the sequence number, so sector n's saved trailer is entry n+1.
const coveredSectors = Math.max(0, usaCount - 1);
if (!updateSequenceArrayFits(usaOffset, usaCount, sectors))
return {
sequenceNumber: 0,
entries: usaCount,
verifiedSectors: 0,
coveredSectors: 0,
mismatchSector: null,
malformed: true,
};
const sequenceNumber = view.getUint16(usaOffset, true);
if (sequenceNumber === 0 || sequenceNumber === 0xffff)
return {
sequenceNumber,
entries: usaCount,
verifiedSectors: 0,
coveredSectors,
mismatchSector: null,
malformed: true,
};
for (let sector = 0; sector < coveredSectors; sector += 1) {
const trailerOffset = sector * FIXUP_SECTOR_BYTES + FIXUP_SECTOR_BYTES - 2;
if (view.getUint16(trailerOffset, true) !== sequenceNumber)
return {
sequenceNumber,
entries: usaCount,
verifiedSectors: sector,
coveredSectors,
mismatchSector: sector,
malformed: false,
};
}
return {
sequenceNumber,
entries: usaCount,
verifiedSectors: coveredSectors,
coveredSectors,
mismatchSector: null,
malformed: false,
};
};
/** Buffer the admitted input once while accepting arbitrary chunk boundaries. */
class StreamingMftDecoder implements RegionDecoder<MftInventory> {
readonly #bytes: Uint8Array;
#written = 0;
constructor(fileBytes: number) {
this.#bytes = new Uint8Array(fileBytes);
}
write(chunk: Uint8Array): Result<void, RegionDecodeFailure> {
if (chunk.length > this.#bytes.length - this.#written)
return err(failure("received more bytes than the admitted file length"));
this.#bytes.set(chunk, this.#written);
this.#written += chunk.length;
return ok(undefined);
}
finish(): Result<MftInventory, RegionDecodeFailure> {
if (this.#written !== this.#bytes.length)
return err(failure("stream ended before the admitted file length"));
return scanMft(this.#bytes);
}
}
export const createMftDecoder = (
fileBytes: number,
): Result<RegionDecoder<MftInventory>, RegionDecodeFailure> =>
Number.isSafeInteger(fileBytes) &&
fileBytes >= 0 &&
fileBytes <= MFT_MAX_FILE_BYTES
? ok(new StreamingMftDecoder(fileBytes))
: err(
limit(
`file is ${String(fileBytes)} bytes, exceeding the fixed ${String(MFT_MAX_FILE_BYTES)}-byte (512 MiB) ceiling`,
"file-size",
),
);
-20
View File
@@ -1,4 +1,3 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -1120,25 +1119,6 @@ describe("Ghidra native instruction decoder context for ARM TMode and MIPS ISA_M
});
});
describe("Ghidra bridge script processor context contract", () => {
it("binds TMode to ARM and ISA_MODE to MIPS in ReaGhidraBridge.java", async () => {
const bridgePath = new URL(
"../../bridge/ghidra/ReaGhidraBridge.java",
import.meta.url,
);
const content = await readFile(bridgePath, "utf8");
expect(content).toContain(
'currentProgram.getLanguageID().getIdAsString().startsWith("ARM:")',
);
expect(content).toContain(
'currentProgram.getLanguageID().getIdAsString().startsWith("MIPS:")',
);
expect(content).toContain('"TMode"');
expect(content).toContain('"ISA_MODE"');
expect(content).toContain('"ghidra-program-context"');
});
});
describe("Ghidra dossier nested boundary composition", () => {
const identityLocations = [
"caller",
@@ -0,0 +1,53 @@
import {
ArtifactResourceScope,
type ArtifactResourceOwner,
} from "../../artifacts/ArtifactResourceScope.js";
/** Retain a cancelled response branch until its underlying cancellation settles. */
export class StateResponseCleanup {
readonly #scope = new ArtifactResourceScope();
constructor(private readonly changed: () => void = () => {}) {}
get cleanupResources(): readonly string[] {
return this.#scope.cleanupResources;
}
cancel(cancel: () => Promise<void>): void {
let state:
| { status: "pending" }
| { status: "done" }
| { status: "failed"; cause: unknown } = { status: "pending" };
const owner: ArtifactResourceOwner = {
kind: "lease",
resource: "state response body",
lease: {
release: async () => {
if (state.status === "pending")
throw new Error("State response cancellation is still pending");
if (state.status === "failed") throw state.cause;
},
},
};
this.#scope.retain(owner);
this.changed();
void Promise.resolve()
.then(cancel)
.then(
async () => {
state = { status: "done" };
await this.#scope.release(owner);
this.changed();
},
(cause: unknown) => {
state = { status: "failed", cause };
this.changed();
},
)
.catch(() => undefined);
}
close(): Promise<void> {
return this.#scope.close();
}
}
+12 -3
View File
@@ -1,3 +1,4 @@
import { StateResponseCleanup } from "./StateResponseCleanup.js";
import type { EnvironmentStateStore } from "../../application/environment/environmentStateStore.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
@@ -46,17 +47,24 @@ interface CallContext {
readonly intake: StateIntake;
readonly cancel: AbortSignal;
readonly files: ArtifactResourceScope;
readonly responses: StateResponseCleanup;
}
/** `data/add`: exactly one part, whose document replaces the whole state only when it is valid and the call was not cancelled. */
const addState = async (
{ store, intake, cancel, files }: CallContext,
{ store, intake, cancel, files, responses }: CallContext,
params: unknown,
): Promise<RpcOutcome> => {
const parts = isRecord(params) ? params.parts : undefined;
if (!Array.isArray(parts) || parts.length !== 1)
return { error: invalidParams("data/add takes exactly one part") };
const document = await partDocument(parts[0], intake, cancel, files);
const document = await partDocument(
parts[0],
intake,
cancel,
files,
responses,
);
if (!document.ok) return { error: document.error };
// A file read is not interruptible, so a cancellation during it is honoured here, before the state changes.
if (cancel.aborted) return { error: CANCELLED };
@@ -101,6 +109,7 @@ export const stateDataPlane = (
intake: StateIntake = DEFAULT_STATE_INTAKE,
stopped: AbortSignal = new AbortController().signal,
files: ArtifactResourceScope = new ArtifactResourceScope(),
responses: StateResponseCleanup = new StateResponseCleanup(),
): RpcMethods => {
let previous: Promise<unknown> = Promise.resolve();
return (method, params, signal) => {
@@ -111,7 +120,7 @@ export const stateDataPlane = (
const next = previous.then(() =>
cancel.aborted
? { error: CANCELLED }
: run({ store, intake, cancel, files }, params),
: run({ store, intake, cancel, files, responses }, params),
);
previous = next.catch(() => undefined);
return next;
+43 -1
View File
@@ -1,3 +1,4 @@
import { StateResponseCleanup } from "./StateResponseCleanup.js";
import type { HttpHostname } from "../../domain/httpHostname.js";
import { STATE_INTAKE_LIMIT_BYTES } from "../../application/environment/environmentStateDocument.js";
import {
@@ -477,6 +478,8 @@ export const serveEnvironment = async (
};
// A state file whose close failed stays owned here: later file reads retry it, and close reports it if it is still open.
const stateFiles = new ArtifactResourceScope();
let responseStateChanged = (): void => undefined;
const stateResponses = new StateResponseCleanup(() => responseStateChanged());
const served = await serveStreamableHttp({
host,
port,
@@ -499,6 +502,7 @@ export const serveEnvironment = async (
},
stopping.signal,
stateFiles,
stateResponses,
),
),
...(logger === undefined ? {} : { logger }),
@@ -512,11 +516,14 @@ export const serveEnvironment = async (
});
let httpClosePending = false;
let stateClosePending = false;
let responseClosePending = false;
let settledSuccessful = false;
let closing: Promise<void> | undefined;
const shutdownFailures = new Set<AnalysisError>();
const owner: EnvironmentShutdownOwner = {
get cleanupResources() {
const stateResources = stateFiles.cleanupResources;
const responseResources = stateResponses.cleanupResources;
return [
...(httpClosePending ? [served.url] : []),
...(stateClosePending
@@ -524,6 +531,11 @@ export const serveEnvironment = async (
? stateResources
: ["environment state-file scope"]
: []),
...(responseClosePending
? responseResources.length > 0
? responseResources
: ["state response cleanup"]
: []),
];
},
close: () => {
@@ -531,7 +543,7 @@ export const serveEnvironment = async (
const attempt = (async () => {
stop();
const failures: {
readonly stage: "http-server" | "state-files";
readonly stage: "http-server" | "state-files" | "state-responses";
readonly cause: unknown;
}[] = [];
try {
@@ -548,6 +560,15 @@ export const serveEnvironment = async (
stateClosePending = true;
failures.push({ stage: "state-files", cause });
}
try {
await stateResponses.close();
if (stateResponses.cleanupResources.length > 0)
throw new Error("State response cleanup remains pending");
responseClosePending = false;
} catch (cause: unknown) {
responseClosePending = true;
failures.push({ stage: "state-responses", cause });
}
if (failures.length > 0) {
retainedEnvironmentShutdowns.add(owner);
const failure = new AnalysisOutputError(
@@ -583,6 +604,7 @@ export const serveEnvironment = async (
retainedEnvironmentShutdowns.delete(owner);
for (const failure of shutdownFailures) failure.resolveCleanup();
shutdownFailures.clear();
settledSuccessful = true;
})();
closing = attempt;
void attempt.catch(() => {
@@ -591,6 +613,26 @@ export const serveEnvironment = async (
return attempt;
},
};
// A fetcher may hand back a response after an earlier stop completed. Keep
// that newly acquired body owned and make a later close observe its outcome.
responseStateChanged = () => {
if (!stopping.signal.aborted) return;
if (stateResponses.cleanupResources.length > 0) {
responseClosePending = true;
retainedEnvironmentShutdowns.add(owner);
if (settledSuccessful) {
settledSuccessful = false;
closing = undefined;
}
} else if (
shutdownFailures.size === 0 &&
!httpClosePending &&
!stateClosePending
) {
responseClosePending = false;
retainedEnvironmentShutdowns.delete(owner);
}
};
return ok({
...served,
card,
@@ -1037,7 +1037,122 @@ describe("serveEnvironment with a state", () => {
expect(missing.isError).toBe(true);
});
});
});
describe("state response cleanup", () => {
it("reports pending teed response cleanup and retries after its sibling closes", async () => {
let sourceCancelled = false;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1]));
},
cancel() {
sourceCancelled = true;
},
});
const [body, sibling] = stream.tee();
const environment = await serveState(
{ source, state },
{
fetchState: async () =>
new Response(body, {
headers: { "content-length": String(STATE_INTAKE_LIMIT_BYTES + 1) },
}),
},
);
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const response = await fetch(
new URL(ENVIRONMENT_RPC_PATH, environment.url),
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(addByUri(1)),
signal: AbortSignal.timeout(10_000),
},
);
await expect(response.json()).resolves.toMatchObject({
error: { code: -32602 },
});
const closing = Promise.race([
environment.close(),
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error("server close waited for tee sibling")),
10_000,
);
}),
]);
await expect(closing).rejects.toMatchObject({
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
diagnostics: { cleanup_stages: ["state-responses"] },
});
expect(sourceCancelled).toBe(false);
await sibling.cancel();
expect(sourceCancelled).toBe(true);
await expect(environment.close()).resolves.toBeUndefined();
} finally {
if (timer !== undefined) clearTimeout(timer);
await Promise.allSettled([body.cancel(), sibling.cancel()]);
await environment.close();
}
});
it("retains a late response cleanup after an earlier successful stop", async () => {
let giveResponse!: (response: Response) => void;
const gate = new Promise<Response>((resolve) => {
giveResponse = resolve;
});
const held = heldFetcher(() => gate);
let release!: () => void;
let acknowledge!: () => void;
const cleanup = new Promise<void>((resolve) => {
release = resolve;
});
const entered = new Promise<void>((resolve) => {
acknowledge = resolve;
});
const environment = await serveState(
{ source, state },
{ fetchState: held.fetchState },
);
const answered = fetch(new URL(ENVIRONMENT_RPC_PATH, environment.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(addByUri(1)),
signal: AbortSignal.timeout(10_000),
}).catch(() => undefined);
try {
await held.fetching;
await environment.close();
giveResponse(
new Response(
new ReadableStream<Uint8Array>({
cancel() {
acknowledge();
return cleanup;
},
}),
),
);
await entered;
await expect(environment.close()).rejects.toMatchObject({
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
diagnostics: { cleanup_stages: ["state-responses"] },
});
release();
await expect(environment.close()).resolves.toBeUndefined();
} finally {
release();
await answered;
await environment.close();
}
});
});
describe("serveEnvironment state file cleanup", () => {
it("stops without waiting for a stalled download", async () => {
const held = heldFetcher(() => new Promise<Response>(() => undefined));
const environment = await serveState(
+110
View File
@@ -1,3 +1,4 @@
import { StateResponseCleanup } from "./StateResponseCleanup.js";
import { expect, it, vi } from "vitest";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
@@ -11,14 +12,17 @@ import {
const inlineDocument = async (bytes: string) => {
const files = new ArtifactResourceScope();
const responses = new StateResponseCleanup();
try {
return await partDocument(
{ kind: "file", file: { bytes } },
DEFAULT_STATE_INTAKE,
new AbortController().signal,
files,
responses,
);
} finally {
await responses.close();
await files.close();
}
};
@@ -79,3 +83,109 @@ it("downloads with redirects refused and the 30 s timeout by default", async ()
fetched.mockRestore();
}
});
it.each(["http-status", "declared-overflow", "stream-overflow"] as const)(
"returns %s while a teed response's other branch remains open",
async (scenario) => {
const source = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
new Uint8Array(
scenario === "stream-overflow" ? STATE_INTAKE_LIMIT_BYTES + 1 : 1,
),
);
},
});
const [body, sibling] = source.tee();
const response = new Response(body, {
status: scenario === "http-status" ? 503 : 200,
...(scenario === "declared-overflow"
? {
headers: { "content-length": String(STATE_INTAKE_LIMIT_BYTES + 1) },
}
: {}),
});
const files = new ArtifactResourceScope();
const responses = new StateResponseCleanup();
const operation = partDocument(
{ kind: "file", file: { uri: "https://state.example.test/state.json" } },
{ fetchState: async () => response, timeoutMs: 1_000 },
new AbortController().signal,
files,
responses,
);
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const outcome = await Promise.race([
operation.then((result) => ({ kind: "result" as const, result })),
new Promise<{ kind: "deadline" }>((resolve) => {
timer = setTimeout(() => resolve({ kind: "deadline" }), 3_000);
}),
]);
expect(outcome.kind).toBe("result");
expect(responses.cleanupResources).toEqual(["state response body"]);
await expect(responses.close()).rejects.toMatchObject({
reason: "unavailable",
});
if (outcome.kind === "result") {
expect(outcome.result).toMatchObject(
scenario === "http-status"
? { ok: false, error: { data: { reason: "http-status" } } }
: {
ok: false,
error: {
message: expect.stringContaining(
String(STATE_INTAKE_LIMIT_BYTES),
),
},
},
);
}
} finally {
if (timer !== undefined) clearTimeout(timer);
await sibling.cancel();
await operation;
await responses.close();
await files.close();
}
},
);
it("retains the exact failure when response cancellation rejects", async () => {
const failure = new Error("controlled cancellation failure");
const body = new ReadableStream<Uint8Array>({
cancel() {
throw failure;
},
});
const files = new ArtifactResourceScope();
const responses = new StateResponseCleanup();
const result = await partDocument(
{ kind: "file", file: { uri: "https://state.example.test/state.json" } },
{
fetchState: async () => new Response(body, { status: 503 }),
timeoutMs: 1_000,
},
new AbortController().signal,
files,
responses,
);
expect(result).toMatchObject({
ok: false,
error: { data: { reason: "http-status" } },
});
await new Promise<void>((resolve) => setImmediate(resolve));
const rejected: unknown = await responses
.close()
.catch((cause: unknown) => cause);
expect(rejected).toMatchObject({
reason: "unavailable",
cleanup: { resources: ["state response body"] },
});
expect((rejected as Error).cause).toBeInstanceOf(AggregateError);
expect(((rejected as Error).cause as AggregateError).errors).toContain(
failure,
);
expect(responses.cleanupResources).toEqual(["state response body"]);
await files.close();
});
+18 -7
View File
@@ -1,3 +1,4 @@
import { StateResponseCleanup } from "./StateResponseCleanup.js";
import { fileURLToPath } from "node:url";
import { mediaTypeEssence } from "../../domain/analysisView/recordedMediaType.js";
@@ -228,6 +229,7 @@ const downloadBounds = (
const readCapped = async (
body: ReadableStream<Uint8Array> | null,
bounds: DownloadBounds,
responses: StateResponseCleanup,
): Promise<Result<Buffer, RpcError>> => {
if (body === null) return ok(Buffer.alloc(0));
const reader = body.getReader();
@@ -240,13 +242,15 @@ const readCapped = async (
if (done) return ok(Buffer.concat(chunks, total));
total += value.byteLength;
if (total > STATE_INTAKE_LIMIT_BYTES) {
await reader.cancel().catch(() => undefined);
// A tee's sibling can be caller-owned; cancelling this branch must not
// delay the refusal until that sibling finishes.
responses.cancel(() => reader.cancel());
return err(TOO_LARGE);
}
chunks.push(value);
}
} catch {
void reader.cancel().catch(() => undefined);
responses.cancel(() => reader.cancel());
return err(fetchFailed(bounds.failure()));
}
};
@@ -256,6 +260,7 @@ const downloadState = async (
url: URL,
intake: StateIntake,
cancel: AbortSignal,
responses: StateResponseCleanup,
): Promise<Result<Buffer, RpcError>> => {
const bounds = downloadBounds(intake.timeoutMs, cancel);
const fetching = Promise.resolve().then(() =>
@@ -268,7 +273,9 @@ const downloadState = async (
// A response that arrives after the download ended is released unread.
void fetching
.then(
(late) => late.body?.cancel(),
(late) => {
if (late.body !== null) responses.cancel(() => late.body!.cancel());
},
() => undefined,
)
.catch(() => undefined);
@@ -276,7 +283,8 @@ const downloadState = async (
}
const declared = Number(response.headers.get("content-length") ?? "0");
if (!response.ok || declared > STATE_INTAKE_LIMIT_BYTES) {
await response.body?.cancel().catch(() => undefined);
// Cancel this branch without waiting for a potentially independent tee sibling.
if (response.body !== null) responses.cancel(() => response.body!.cancel());
return err(
response.ok
? TOO_LARGE
@@ -286,7 +294,7 @@ const downloadState = async (
},
);
}
return readCapped(response.body, bounds);
return readCapped(response.body, bounds, responses);
};
const NETWORK_SHARE = invalidParams(
@@ -315,6 +323,7 @@ const fileBytes = async (
intake: StateIntake,
cancel: AbortSignal,
files: ArtifactResourceScope,
responses: StateResponseCleanup,
): Promise<Result<Uint8Array, RpcError>> => {
if (typeof file.bytes === "string" && file.uri === undefined) {
if (file.bytes.length > MAX_INLINE_BASE64_CHARACTERS) return err(TOO_LARGE);
@@ -333,7 +342,8 @@ const fileBytes = async (
invalidParams("a file part carries exactly one of bytes or a uri"),
);
const url = new URL(file.uri);
if (url.protocol === "https:") return downloadState(url, intake, cancel);
if (url.protocol === "https:")
return downloadState(url, intake, cancel, responses);
if (url.protocol !== "file:")
return err(invalidParams("a file uri is a file:// or https:// URL"));
const path = localFilePath(url);
@@ -346,6 +356,7 @@ export const partDocument = async (
intake: StateIntake,
cancel: AbortSignal,
files: ArtifactResourceScope,
responses: StateResponseCleanup,
): Promise<Result<unknown, RpcError>> => {
if (isRecord(part) && part.kind === "data" && isRecord(part.data))
return ok(part.data);
@@ -362,6 +373,6 @@ export const partDocument = async (
mediaTypeEssence(mimeType) !== "application/json")
)
return err(invalidParams("a file part's mimeType is application/json"));
const bytes = await fileBytes(part.file, intake, cancel, files);
const bytes = await fileBytes(part.file, intake, cancel, files, responses);
return bytes.ok ? parseDocumentBytes(bytes.value) : bytes;
};
@@ -15,6 +15,13 @@ const cases = [
0,
],
['spawn("control", [], {stdio:"inherit"})', "control", "inherit", 0],
['spawn("global-nan-env", [], {env:NaN})', "global-nan-env", "default", 0],
[
'((NaN) => spawn("shadowed-nan-env", [], {env:NaN}))({})',
"shadowed-nan-env",
"default",
0,
],
[
'spawn("spread-after", [], {stdio:"pipe",...input})',
"spread-after",
@@ -233,6 +240,12 @@ const exportAssignmentSource = `
export = argv;
`;
const environmentCommands = [
"named-argv",
"execfile-dynamic",
"shadowed-nan-env",
];
// Callback/options ambiguity cannot change exec's effective stdio.
const opaqueExecCallbackCommands = [
"eval-callback",
@@ -342,7 +355,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
expect(child.properties.stdio_mode, String(command)).toBe(mode);
expect(child.properties.argv_count, String(command)).toBe(count);
expect(child.properties.environment_supplied, String(command)).toBe(
["named-argv", "execfile-dynamic"].includes(String(command)),
environmentCommands.includes(String(command)),
);
expect(child.identity.source_range).not.toBeNull();
const stdio = graph.relations.filter(
@@ -377,9 +390,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
relation.relation === "supplies-env" &&
relation.target_node_id === child.node_id,
),
).toHaveLength(
["named-argv", "execfile-dynamic"].includes(String(command)) ? 1 : 0,
);
).toHaveLength(environmentCommands.includes(String(command)) ? 1 : 0);
expect(
graph.relations.filter(
(relation) =>
@@ -1,81 +1,72 @@
import { execFile } from "node:child_process";
import { readFile, readdir, writeFile } from "node:fs/promises";
import { readFile, readdir } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { expect } from "vitest";
import { parse } from "yaml";
import { resolveSwiftcCompileTimeoutMs } from "../../../src/process/DarwinProcessRunTokenReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { processTest } from "../../support/process/processFixture.js";
const execute = promisify(execFile);
const hostLabels: Partial<Record<NodeJS.Platform, string>> = {
linux: "linux",
darwin: "macOS",
win32: "Windows",
};
const hostLabel = hostLabels[process.platform];
const preparationBudget =
process.platform === "darwin" ? resolveSwiftcCompileTimeoutMs() : 0;
it("enforces workflow platform labels before contacting Cutter", async () => {
const workflow = parse(
await readFile(".github/workflows/real-cutter.yml", "utf8"),
);
const labels = workflow.jobs["cutter-upstream"].strategy.matrix.include.map(
(entry: { platform: string }) => entry.platform,
);
expect(labels).toEqual(["linux", "macOS", "Windows"]);
const root = await createTestTempDirectory("rea-cutter-platform-");
const preload = join(root, "preload.mjs");
await writeFile(
preload,
`
import childProcess from 'node:child_process';
import { syncBuiltinESMExports } from 'node:module';
Object.defineProperty(process, 'platform', { value: process.env.REA_PROBE_PLATFORM });
childProcess.execFile = () => { throw new Error('fixture discovery reached'); };
syncBuiltinESMExports();
`,
);
const check = async (selected: string | undefined, actual: string) => {
const env: NodeJS.ProcessEnv = {
...process.env,
TMPDIR: root,
TMP: root,
TEMP: root,
REA_PROBE_PLATFORM: actual,
processTest.skipIf(hostLabel === undefined)(
"enforces workflow platform labels before contacting Cutter",
{ timeout: Math.min(2_147_483_647, 2 * preparationBudget + 30_000) },
async ({ processes }) => {
const workflow = parse(
await readFile(".github/workflows/real-cutter.yml", "utf8"),
);
const labels = workflow.jobs["cutter-upstream"].strategy.matrix.include.map(
(entry: { platform: string }) => entry.platform,
);
expect(labels).toEqual(["linux", "macOS", "Windows"]);
const root = await createTestTempDirectory("rea-cutter-platform-");
// A private absent directory proves actual discovery without contacting a user's bridge.
const bridgeDirectory = join(root, "absent-bridge");
const check = async (selected: string | undefined) => {
const env: NodeJS.ProcessEnv = {
...process.env,
TMPDIR: root,
TMP: root,
TEMP: root,
REA_CUTTER_BRIDGE_DIR: bridgeDirectory,
};
if (selected === undefined) delete env.EXPECTED_PLATFORM;
else env.EXPECTED_PLATFORM = selected;
const result = await processes.run(
process.execPath,
["scripts/verify-real-cutter.mjs"],
{
env,
timeoutMs: Math.min(2_147_483_647, preparationBudget + 15_000),
},
);
expect(result.exitCode, result.stderr).toBe(1);
return result.stderr;
};
if (selected === undefined) delete env.EXPECTED_PLATFORM;
else env.EXPECTED_PLATFORM = selected;
const result: unknown = await execute(
process.execPath,
["--import", preload, "scripts/verify-real-cutter.mjs"],
{ env, timeout: 10_000 },
).then(
() => {
throw new Error("Fixture discovery should stop the verifier");
},
(error: unknown) => error,
for (const selected of [hostLabel, undefined]) {
const stderr = await check(selected);
expect(stderr).toContain("Open upstream Cutter with the REA plugin");
expect(stderr).toContain("no_live_bridge_found");
}
const other = labels.find((label: string) => label !== hostLabel);
expect(other).toBeDefined();
expect(await check(other)).toContain(
"Cutter runner did not match its declared platform",
);
if (
!(result instanceof Error) ||
!("stderr" in result) ||
typeof result.stderr !== "string"
)
throw new Error("Missing verifier diagnostics");
return result.stderr;
};
for (const [selected, actual] of [
["linux", "linux"],
["macOS", "darwin"],
["Windows", "win32"],
] as const)
expect(await check(selected, actual)).toContain(
"fixture discovery reached",
expect(await check("unknown")).toContain(
"Unrecognized Cutter runner platform",
);
expect(await check("linux", "darwin")).toContain(
"Cutter runner did not match its declared platform",
);
expect(await check("unknown", "linux")).toContain(
"Unrecognized Cutter runner platform",
);
expect(await check(undefined, "linux")).toContain(
"fixture discovery reached",
);
expect(
(await readdir(root)).filter((name) =>
name.startsWith("rea-cutter-smoke-"),
),
).toEqual([]);
});
expect(
(await readdir(root)).filter((name) =>
name.startsWith("rea-cutter-smoke-"),
),
).toEqual([]);
},
);
@@ -783,7 +783,7 @@ it.each([
{ code: false, ghidra_bridge: true, runtime: false, package: false },
],
[
"tests/conformance/ghidra/ReaArmContextProbe.java",
"tests/conformance/ghidra/ReaInstructionContextProbe.java",
{ ghidra_bridge: true, runtime: false, package: false },
],
[
+1 -2
View File
@@ -4,7 +4,6 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { isPortableBundleName } from "../../../src/application/environment/environmentBundle.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseDesktopTask } from "../../../src/domain/desktop/appTask.js";
import {
@@ -40,7 +39,7 @@ const README = "# Notes computer app\n\n## Task `set-year`\n\nThe task.\n";
/** A bundle holding TASK as the export writes it, with its README. */
const bundleWithTask = async () => {
const parsed = parseDesktopTask(TASK, isPortableBundleName);
const parsed = parseDesktopTask(TASK);
if (!parsed.ok) throw new Error(parsed.error);
const bundle = await createTestTempDirectory("measured-bundle-");
const steps = renderTaskSteps(parsed.value, "notes");
+1 -2
View File
@@ -12,7 +12,6 @@ import { gzipSync } from "node:zlib";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { expect, it, vi } from "vitest";
import { isPortableBundleName } from "../../../src/application/environment/environmentBundle.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseDesktopTask } from "../../../src/domain/desktop/appTask.js";
import {
@@ -142,7 +141,7 @@ const lines = (...text: string[]) => ({
/** A bundle folder holding TASK as the export writes it for the app. */
const taskBundle = async (app: string) => {
const parsed = parseDesktopTask(TASK, isPortableBundleName);
const parsed = parseDesktopTask(TASK);
if (!parsed.ok) throw new Error(parsed.error);
const bundle = await bundleFolder();
const verifier = join(
+10 -7
View File
@@ -8,7 +8,6 @@ import type {
BuildSettle,
SettleClock,
} from "../../../src/application/desktop/DesktopBuildSettle.js";
import { isPortableBundleName } from "../../../src/application/environment/environmentBundle.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import type { SettleTiming } from "../../../src/domain/desktop/appSettle.js";
import { parseDesktopTask } from "../../../src/domain/desktop/appTask.js";
@@ -58,7 +57,7 @@ const lines = (...text: string[]) => ({
/** A bundle folder holding `task` as the export writes it for the app. */
const taskBundle = async (task: unknown, app: string) => {
const parsed = parseDesktopTask(task, isPortableBundleName);
const parsed = parseDesktopTask(task);
if (!parsed.ok) throw new Error(parsed.error);
const bundle = await bundleFolder();
const verifier = join(
@@ -516,11 +515,15 @@ it("ends the witness when the seed already passes, and refuses its later stages"
parsed(await check({ task: passing, stage: "seed", directory })).witness,
).toEqual(seed.witness);
const elsewhere = `${directory}-elsewhere`;
expect(
parseMcpToolError(
await check({ task: passing, stage: "seed", directory: elsewhere }),
).error.message,
).toContain(`saved to ${directory}, not ${elsewhere}`);
const refusal = parseMcpToolError(
await check({ task: passing, stage: "seed", directory: elsewhere }),
).error;
expect(refusal).toMatchObject({
code: "invalid_request",
message: expect.stringContaining(
`record belongs to ${directory}, not ${elsewhere}`,
),
});
await act("type", { text: "eggs\n" });
expect(
parseMcpToolError(await check({ task: passing, stage: "after_edit" })).error
@@ -0,0 +1,84 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
import { serveCli } from "../cli/cliServeHarness.js";
const expectMftInventory = (value: unknown): void => {
const evidence = parseEvidence(value);
const inspection = artifactInspectionResultSchema.parse(
evidence.normalized_result,
);
const inventory = inspection.substeps[0]?.evidence.normalized_result;
expect(inventory?.manifest.root_format).toBe("ntfs-mft");
expect(inventory?.occurrences[0]?.format_metadata).toMatchObject({
kind: "ntfs-mft",
record_count: 1,
fixup_unverified_record_count: 0,
record_headers: [
{
index: 0,
fileOffset: 0,
sequenceNumber: 1,
declaredRecordNumber: null,
fixups: { verifiedSectors: 2 },
},
],
omitted_record_headers: 0,
});
};
mcpTest(
"admits an MFT capture by signature through CLI and MCP",
async ({ mcp, onTestFinished }) => {
const root = await createTestTempDirectory("rea-ntfs-mft-admission-");
const path = join(root, "capture.bin");
const record = Buffer.alloc(1024);
record.write("FILE");
record.writeUInt16LE(42, 4);
record.writeUInt16LE(3, 6);
record.writeUInt16LE(1, 16);
record.writeUInt16LE(56, 20);
record.writeUInt32LE(64, 24);
record.writeUInt32LE(0xffff_ffff, 56);
record.writeUInt32LE(1024, 28);
record.writeUInt16LE(5, 42);
record.writeUInt16LE(5, 510);
record.writeUInt16LE(5, 1022);
await writeFile(path, record);
const cli = await serveCli(["inspect-artifact", path, "--json"]);
expect(cli.exitCode, cli.stdout).toBe(0);
expectMftInventory(JSON.parse(cli.stdout));
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(configured.value, silentLogger, {});
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(true);
expectMftInventory(inspected.structuredContent);
},
);
@@ -1,4 +1,4 @@
import { readFile, writeFile } from "node:fs/promises";
import { readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect } from "vitest";
@@ -175,7 +175,11 @@ registerHooks({ load(url, context, nextLoad) {
),
],
{
env: { ...process.env, REA_AGENT_EVAL_ROOT: parent },
env: {
...process.env,
REA_AGENT_EVAL_ROOT: parent,
REA_AGENT_EVAL_KEEP_FIXTURES: "false",
},
timeoutMs: 10_000,
},
);
@@ -190,14 +194,13 @@ registerHooks({ load(url, context, nextLoad) {
if (incomplete) {
expect(result.stderr).toContain("Artifact cleanup remains incomplete");
expect(result.stderr).toContain("fixture cleanup denied");
expect(await readFile(join(run, "codex/auth.json"), "utf8")).toBe(
"inert fixture",
);
expect((await stat(run)).isDirectory()).toBe(true);
} else {
await expect(
readFile(join(run, "codex/auth.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(stat(run)).rejects.toMatchObject({ code: "ENOENT" });
}
await expect(readFile(join(run, "codex/auth.json"))).rejects.toMatchObject({
code: "ENOENT",
});
},
);
@@ -274,7 +277,11 @@ registerHooks({ load(url, context, nextLoad) {
),
],
{
env: { ...process.env, REA_AGENT_EVAL_ROOT: parent },
env: {
...process.env,
REA_AGENT_EVAL_ROOT: parent,
REA_AGENT_EVAL_KEEP_FIXTURES: "false",
},
timeoutMs: 10_000,
},
);
@@ -298,13 +305,14 @@ registerHooks({ load(url, context, nextLoad) {
if (incomplete) {
expect(result.stderr).toContain("Artifact cleanup remains incomplete");
expect(result.stderr).toContain("darwin-fixture-reader");
expect(
await readFile(join(observed.run, "codex/auth.json"), "utf8"),
).toBe("inert preparation fixture");
expect((await stat(observed.run)).isDirectory()).toBe(true);
} else {
await expect(
readFile(join(observed.run, "codex/auth.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(stat(observed.run)).rejects.toMatchObject({
code: "ENOENT",
});
}
await expect(
readFile(join(observed.run, "codex/auth.json")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -1,24 +1,57 @@
import { execFile } from "node:child_process";
import {
copyFile,
cp,
mkdir,
readFile,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { join, resolve } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { processTest } from "../../support/process/processFixture.js";
import { resolveSwiftcCompileTimeoutMs } from "../../../src/process/DarwinProcessRunTokenReader.js";
const execute = promisify(execFile);
const preparationBudget =
process.platform === "darwin" ? resolveSwiftcCompileTimeoutMs() : 0;
async function prepareController(controller: string, version: string) {
// The verifier loads its production-owned TypeScript source graph at runtime.
// Keep that graph in the isolated controller so imports cannot drift from a hand-maintained list.
await mkdir(join(controller, "scripts"), { recursive: true });
await copyFile(
"scripts/verify-release-artifact.mjs",
join(controller, "scripts/verify-release-artifact.mjs"),
);
await cp("scripts/lib", join(controller, "scripts/lib"), {
recursive: true,
});
await mkdir(join(controller, "bridge"), { recursive: true });
await cp("bridge/process", join(controller, "bridge/process"), {
recursive: true,
});
await cp("src", join(controller, "src"), {
recursive: true,
filter: (source) => !/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(source),
});
await writeFile(
join(controller, "package.json"),
JSON.stringify({ name: "rea-agents", version, type: "module" }),
);
await symlink(
resolve("node_modules"),
join(controller, "node_modules"),
process.platform === "win32" ? "junction" : "dir",
);
}
// Release rehearsal runs on Linux; the npm process adapter is also exercised on macOS.
it.skipIf(process.platform === "win32")(
processTest.skipIf(process.platform === "win32")(
"fails without declared runtime, then rehearses an installed tarball and rejects catalog drift",
async () => {
{ timeout: Math.min(2_147_483_647, 3 * preparationBudget + 210_000) },
async ({ processes }) => {
const root = await createTestTempDirectory("rea-release-canary-");
const candidate = join(root, "candidate");
const controller = join(root, "controller");
@@ -76,56 +109,46 @@ if (process.argv[2] === "mcp") {
} else { process.exitCode = 1; }
`,
);
const packed = await execute(
"npm",
["pack", "--ignore-scripts", "--json"],
{
cwd: candidate,
},
);
const pack = async () => {
const result = await processes.run(
"npm",
["pack", "--ignore-scripts", "--json"],
{ cwd: candidate, timeoutMs: 30_000 },
);
expect(result.exitCode, result.stderr).toBe(0);
return result;
};
const packed = await pack();
const [{ filename }] = z
.tuple([z.object({ filename: z.string() })])
.parse(JSON.parse(packed.stdout));
const tarball = join(candidate, filename);
for (const file of [
"scripts/verify-release-artifact.mjs",
"scripts/lib/release-package-canary.mjs",
"scripts/lib/verify-package-core.mjs",
"scripts/lib/mcp-verifier-results.mjs",
"scripts/lib/verifier-run.mjs",
]) {
const target = join(controller, file);
await mkdir(dirname(target), { recursive: true });
await copyFile(file, target);
}
await writeFile(
join(controller, "package.json"),
JSON.stringify({ name: "rea-agents", version, type: "module" }),
);
await symlink(
resolve("node_modules"),
join(controller, "node_modules"),
process.platform === "win32" ? "junction" : "dir",
);
await prepareController(controller, version);
const invoke = (selected = tarball) =>
execute(
processes.run(
process.execPath,
[
join(controller, "scripts/verify-release-artifact.mjs"),
selected,
version,
],
{ cwd: controller, maxBuffer: 16 * 1024 * 1024 },
{
cwd: controller,
timeoutMs: Math.min(2_147_483_647, preparationBudget + 30_000),
},
);
await expect(invoke()).rejects.toMatchObject({
stderr: expect.stringContaining("ERR_MODULE_NOT_FOUND"),
});
const missing = await invoke();
expect(missing.exitCode).toBe(1);
expect(missing.stderr).toContain("ERR_MODULE_NOT_FOUND");
expect(missing.stderr).toMatch(/dist[/\\]catalogIdentity\.js/u);
await symlink(
resolve("dist"),
join(controller, "dist"),
process.platform === "win32" ? "junction" : "dir",
);
const result = JSON.parse((await invoke()).stdout);
const successful = await invoke();
expect(successful.exitCode, successful.stderr).toBe(0);
const result = JSON.parse(successful.stdout);
expect(result).toMatchObject({
package: "rea-agents",
version,
@@ -144,12 +167,10 @@ if (process.argv[2] === "mcp") {
join(candidate, "scripts/reply.json"),
JSON.stringify(snapshot),
);
await execute("npm", ["pack", "--ignore-scripts", "--json"], {
cwd: candidate,
});
await expect(invoke()).rejects.toMatchObject({
stderr: expect.stringContaining("invalid canonical tool catalog"),
});
await pack();
const drifted = await invoke();
expect(drifted.exitCode).toBe(1);
expect(drifted.stderr).toContain("invalid canonical tool catalog");
await writeFile(
join(candidate, "package.json"),
JSON.stringify({
@@ -159,15 +180,12 @@ if (process.argv[2] === "mcp") {
files: ["scripts"],
}),
);
const wrong = await execute("npm", ["pack", "--ignore-scripts", "--json"], {
cwd: candidate,
});
const wrong = await pack();
const [{ filename: wrongFilename }] = z
.tuple([z.object({ filename: z.string() })])
.parse(JSON.parse(wrong.stdout));
await expect(invoke(join(candidate, wrongFilename))).rejects.toMatchObject({
stderr: expect.stringContaining("Installed package identity"),
});
const mismatched = await invoke(join(candidate, wrongFilename));
expect(mismatched.exitCode).toBe(1);
expect(mismatched.stderr).toContain("Installed package identity");
},
30_000,
);
@@ -157,11 +157,17 @@ async def run():
second = asyncio.create_task(other.verify("http://mcp", "http://computer:8080"))
results, _ = await asyncio.gather(first, second)
return results, first_error
if scenario.get("report_failure"):
try:
await module.verify("http://mcp", "http://computer:8080")
except BaseException as error:
return [], first_error or str(error) + " ".join(getattr(error, "__notes__", ()))
raise AssertionError("the controlled reader failure did not occur")
results = await module.verify("http://mcp", "http://computer:8080")
return results, first_error
results, first_error = asyncio.run(run())
print(json.dumps({"called": called, "reads": reads, "ended": clock[0], "results": results, "execs": execs, "first_error": first_error}))
print(json.dumps({"called": called, "reads": reads, "ended": clock[0], "results": results, "execs": execs, "first_error": first_error, "pending_readers": len(module._PENDING_READERS) if hasattr(module, "_PENDING_READERS") else 0}))
`;
type VerifierOutput = {
@@ -170,6 +176,7 @@ type VerifierOutput = {
reads: number[];
ended: number;
first_error: string | null;
pending_readers: number;
results: {
id: string;
result: boolean;
@@ -194,6 +201,7 @@ const runVerifier = async (
readonly reloadVerifier?: boolean;
readonly concurrent?: boolean;
readonly parallelRetry?: boolean;
readonly reportFailure?: boolean;
} = {},
): Promise<VerifierOutput> => {
const folder = await createTestTempDirectory("desktop-task-python-");
@@ -232,6 +240,7 @@ const runVerifier = async (
reload_verifier: computer.reloadVerifier,
concurrent: computer.concurrent,
parallel_retry: computer.parallelRetry,
report_failure: computer.reportFailure,
}),
encoding: "utf8",
}),
@@ -636,3 +645,60 @@ it.each([
).rejects.toThrow(message);
},
);
it.each([
{ transport: false, pending: 0 },
{ transport: true, pending: 1 },
])(
"preserves completed views and absence when a later reader fails (transport: $transport)",
async ({ transport, pending }) => {
const output = await runVerifier(READER_CHECKS, [[0, CHECK_VIEWS]], [], {
readers: [READERS[0]!, READERS[3]!, READERS[2]!],
answers: {
layers: ANSWERS.layers,
gone: ANSWERS.gone,
...(transport ? {} : { broken: "broken runner answer" }),
},
reportFailure: true,
});
expect(output.first_error).toContain("broken");
const facts =
/completed reader views: (.*); completed reader absent: (.*)$/u.exec(
output.first_error ?? "",
);
expect(facts).not.toBeNull();
expect(JSON.parse(facts![1]!)).toEqual({
layers: (ANSWERS.layers as { view: unknown }).view,
});
expect(JSON.parse(facts![2]!)).toEqual(["gone"]);
expect(output.pending_readers).toBe(pending);
},
);
it.each([false, true])(
"keeps a malformed reader answer primary alongside cleanup and retry (retry: %s)",
async (retry) => {
const output = await runVerifier(READER_CHECKS, [[0, CHECK_VIEWS]], [], {
readers: [READERS[2]!],
answers: { broken: "invalid runner payload" },
cleanupFailures: 1,
reportFailure: true,
retry,
});
expect(output.first_error).toContain("did not answer for broken");
expect(output.first_error).toContain("invalid runner payload");
expect(output.first_error).toContain("permission denied");
expect(output.first_error).toContain("/tmp/rea-reader-");
expect(output.pending_readers).toBe(retry ? 0 : 1);
if (retry) {
const cleanups = output.execs.filter(({ request_id }) =>
String(request_id).startsWith("rea-reader-cleanup-"),
);
expect(cleanups).toHaveLength(3);
const lease = (entry: Record<string, unknown>) =>
JSON.parse((entry.argv as string[])[4]!);
expect(lease(cleanups[1]!)).toEqual(lease(cleanups[0]!));
expect(lease(cleanups[2]!)).not.toEqual(lease(cleanups[0]!));
}
},
);
@@ -35,7 +35,7 @@ const expectUnread = async (source: string) => {
expect(view).toMatchObject({
format: null,
view: null,
error: expect.stringContaining("could not inspect the reader's file"),
error: expect.stringContaining("cannot inspect the reader's source"),
});
if (view === undefined) throw new Error("inspection failure became absence");
const [outcome] = evaluateTaskChecks(
@@ -1,5 +1,5 @@
import { execFile } from "node:child_process";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { access, chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { promisify } from "node:util";
@@ -209,6 +209,66 @@ it("answers absent for a file the home does not hold, without running the reader
await expect(access(join(home, "ran"))).rejects.toThrow();
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"keeps an inaccessible source unknown instead of answering absent",
async () => {
const { home, app } = await computer();
const documents = join(home, "Documents");
await chmod(documents, 0);
try {
const view = readerAnswerView(await run(home, reporting(app)));
expect(view).toMatchObject({ format: null, view: null });
expect(view?.error).toContain("cannot inspect");
} finally {
await chmod(documents, 0o700);
}
},
);
it.each(["json", "lines"] as const)(
"refuses malformed UTF-8 in marked %s output while preserving literal replacement characters",
async (output) => {
const { home } = await computer();
const reader = (bytes: string): DesktopTaskReader => ({
id: "encoding",
file: NOTE,
argv: [
"python3",
"-I",
"-c",
`import sys; sys.stdout.buffer.write(${bytes})`,
"{file}",
],
output,
});
const malformed = readerAnswerView(
await run(home, reader(String.raw`b'REA {"value":"\xff"}\n'`)),
);
expect(malformed).toMatchObject({ format: null, view: null });
expect(malformed?.error).toContain("UTF-8");
const valid = readerAnswerView(
await run(
home,
reader(
String.raw`b'\xff ignored banner\nREA {"value":"\xef\xbf\xbd"}\r\n'`,
),
),
);
expect(valid).toMatchObject(
output === "json"
? { format: "json", view: { value: "\ufffd" } }
: {
format: "text",
view: {
lines: ['{"value":"\ufffd"}'],
line_count: 1,
truncated: false,
},
},
);
},
);
it.each([
[
"exits non-zero",
+6
View File
@@ -21,6 +21,12 @@ no-overwrite CLI delivery. It checks the target and project files for changes.
Clang/LLD/LLVM readelf/LLVM objdump; `REA_RISCV_CLANG`, `REA_RISCV_LLD`,
`REA_RISCV_READELF` and `REA_RISCV_OBJDUMP` select existing tool commands.
- `ReaInstructionContextProbe.java` inspects source-owned ARM, Thumb, MIPS32
and MIPS16 instructions through the production bridge in an ephemeral,
read-only Ghidra project. It checks exact decoder-context register names,
values and provenance; the ARM lane also injects an unavailable provider
value. The `ghidra-bridge-sources` CI job runs both processor families. The
input bytes are never executed.
- `ReaDecodeProbe.java` decodes source-owned instruction bytes from a
language's default context and checks each mnemonic, length and optional
complete operand. The `ghidra-bridge-sources` CI job runs it for `ARM:LE:32:Cortex`,
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more