32 Commits
Author SHA1 Message Date
0f5ab1e042 feat(artifacts): inspect Debian package control metadata and contents (#10689)
* feat(artifacts): inspect Debian package control metadata and contents

* fix(deb): throw ParseFailureError and record the new tool's schema counts

DebPackageFormatFailure now extends ParseFailureError, as the architecture
guard requires of parser failure classes; its kind, partial and message are
unchanged. The advertised-dialect baseline takes the counts the
inspect_deb_package input schema adds ($schema in both profiles, and allOf,
default, examples, the \/ escape, the unanchored path pattern and untyped
nodes in the full profile).

* docs(deb): say dpkg runs maintainer scripts, not dpkg-deb

dpkg-deb only reads the archive; installing with dpkg is what runs the
maintainer scripts. Correct the spec so the safety rationale names the
right tool.

* refactor(deb): project format failures through parseFailureAnalysisError

The provider now maps DebPackageFormatFailure with the shared
parseFailureAnalysisError instead of its own instanceof ladder, passing the
partial ar/control/data observation as diagnostics. The helper takes that
optional diagnostics argument. DebPackageCapacityFailure extends
ParseFailureError<"limit"> with the resource and maximum as its limit, and
the provider keeps its limit recovery.

* test(deb): resolve inspect_deb_package from its contract family

The CLI acceptance and MCP boundary tests now take the contract from
DEB_PACKAGE_TOOL_CONTRACTS instead of the full catalog, as the testing guide
asks of focused contract tests.

* fix(deb): require debian-binary and a control file for complete coverage

Coverage was complete with a missing or empty debian-binary, or a control.tar
that held no control file. It now needs a known format version and the
control file as well as the control and data members, and each gap adds a
limitation.

* fix(deb): count hardlinks in the md5sums path cross-check

dpkg lists every name of a hardlinked file in md5sums, while tar stores the
later names as hardlink entries. The cross-check inventory now takes
hardlink paths as well as regular files, so those names are no longer
counted missing.

* fix(deb): decode xz only when its index declares a size within the limit

The sync @napi-rs/lzma decoder takes no output bound, so a member whose
index could not be read was decoded with no limit and checked only after
allocation. decodeXz now refuses such a member, as truncated when the footer
is missing and malformed otherwise, before calling the decoder.

* fix(deb): leave the md5sums cross-check unknown when an input is unread

md5sums that is not UTF-8 counted as zero listed paths, and a package with
no data.tar counted as an empty inventory. The cross-check is now computed
only when both were read; otherwise it stays null and a limitation says
which input was missing.

* fix(deb): refuse Version and Installed-Size values the output schema rejects

A Version with an empty upstream part or Debian revision (1:, 1:-1, 1.0-)
and an Installed-Size past the safe integer range reached DebControl and
failed the output schema, so the service lost the report. The parser now
records a malformed field issue and leaves the value null.

* build(deb): declare src/deb as a provider module layer

Main now requires every top-level src unit in UNIT_LAYERS. src/deb is a
provider like src/sqlite, and its two type imports of application ports
are recorded in the upward-import baseline the same way. The xz spy
binding now accepts the string or bytes input XzApi.compressSync takes.

* fix(deb): keep tar names and link targets as stored

Read ustar name, prefix and linkname fields, and GNU long names, as
NUL-terminated UTF-8 without trimming or rewriting backslashes, and keep
spaces in md5sums paths. A name that is not UTF-8 is shown with U+FFFD
replacements and counted in a limitation, since it may not match md5sums.

* fix(deb): read control files from the control.tar root only

Look up control, conffiles, md5sums and maintainer scripts by their
normalized root path, so a nested subdir/control or subdir/postinst no
longer stands in for the root file.

* fix(deb): read PAX records by byte length

PAX record lengths count bytes, so walk the extended header bytes and
decode each record on its own. A UTF-8 path no longer swallows part of
the next record. A path or linkpath record that is not UTF-8 is counted
in the same not-UTF-8 limitation as ustar names.

* fix(deb): keep unreadable relationship alternatives as issues

Accept hyphenated architecture qualifiers such as kfreebsd-amd64, and
have parseDebianRelationshipField return the alternatives it cannot
read. parseControl records each as a malformed issue on its field, so
the package reports partial coverage instead of dropping a dependency.

* fix(deb): deliver the whole partial report on a refusal

A Debian package refusal now carries the bounded partial report as
diagnostics.partial, so control facts, relationships, maintainer-script
facts, ar member offsets and file rows read before the failure reach CLI
and MCP callers, not just member names and a count.

* fix(deb): decode only the maintainer script interpreter line

interpreterLine now finds the first newline in the script bytes and
decodes only the #! line, so non-UTF-8 bytes later in the script, or a
cut through a multi-byte character at byte 256, no longer hide a valid
interpreter.

* fix(deb): bound unreadable relationship diagnostics per field

parseDebianRelationshipField now counts unreadable alternatives and keeps
only the first, and parseControl records one issue per field with that
count and the first term cut to 120 characters, so a field of many `|`
separators no longer grows the report with its input.

* test(deb): check parser guidance through its owning formatters

Export undecodableTarNamesLimitation and unreadableRelationshipsDetail
from the parser and assert delivered limitations and issue details
through them, so wording edits change one place.

* fix(deb): bound PAX header work before each tar entry

Keep only the path and linkpath PAX keys the reader uses, set in place
rather than copying an accumulated object per header, and refuse more
than eight GNU long name/link or PAX headers before one entry as
malformed, so a run of short PAX headers cannot stall the server.

* fix(deb): apply PAX owner records to the following entry

PAX uid, gid, uname and gname now override the fixed ustar fields,
which can hold shortened or fallback values. A uid or gid that is not a
safe decimal integer falls back to the fixed field.

* fix(deb): keep GNU ar string tables as counted members

A // string-table member is now kept in the ar inventory and counted
against max_ar_members like any other member. As an unknown role it is
listed in extra_member_names, so coverage reports partial.

* fix(deb): honor PAX size records and escaped md5sums names

- A PAX size record overrides the next entry's ustar size field. Reading
  and skipping by the header field reported an empty file and then parsed
  its data as a header, refusing a valid archive.
- GNU md5sum writes a leading backslash and escapes names that contain a
  backslash, newline or carriage return. Those lines were dropped, so the
  cross-check counted listed files as missing; they are now read, and lines
  that are not digest lines are counted in a limitation.

* fix(deb): bound relationship alternatives and read PAX headers faithfully

- Count relationship alternatives across the control file before building
  any, refusing more than a fixed 65,536; a field of '|' separators within
  the control budget could build millions of report objects.
- Refuse a PAX extended header whose record length is unreadable or runs
  past the member, instead of using the fields read so far.
- Keep global (g) PAX values for every later entry and per-file (x) values
  for the next entry only; global values were cleared after the first file.

* refactor(deb): drop an unused import

* chore(mcp): drop the dialect baseline main retired in #10693

* fix(analysis-view): call completeWithinViewCoverage with main's single count

Main dropped its redundant second argument; both arguments were the same
count here.

* test(mcp): record this PR's advertised-schema summary

Add the advertised-schema summary for inspect_deb_package, generated
with npm run verify:advertised-schemas -- --update-summary.

* fix(deb): bound repeated global PAX text and accept xz stream padding

A global PAX path, linkpath, uname or gname is copied into every later
row, so each reuse is now charged to the member byte budget
(max_data_bytes or max_control_bytes) and refused before the row is
added. An empty global PAX value now deletes the earlier global
override, so later entries read their header owner again.

xzUncompressedSize and the footer check skip trailing zero Stream
Padding in 4-byte groups before locating the footer, so valid padded
xz members are no longer reported as truncated.

* fix(deb): trim trailing tar path slashes with a backward scan

The unanchored /\/+$/u retried from every slash, so a PAX path or
md5sums name made of a long slash run and a final non-slash took
quadratic time. logicalTarPath now trims trailing slashes with a
linear charCodeAt scan from the end.

* fix(deb): parse global PAX owner ids once per global record

Global uid and gid values were run through paxId for every later
entry, and the repeated-text budget skips numeric keys, so a long
global owner value was rescanned once per row. Parse them when the
global record is read and reuse the numbers.

* refactor(deb): report coverage with the shared coverage status schema

* refactor(deb): classify provider failures through classifyProviderFailure

* fix(deb): bound resolved ar member names before copying them

GNU ar /N references can repeat one string-table entry without charging
its text to any budget, and every resolved name is copied into the report
and its Evidence. Refuse a BSD or GNU long name above 4096 bytes before it
is read or sliced, so repeated references cannot expand a small table into
large report text.

* test(deb): register the debPackage capability conformance case

debPackage is declared in CAPABILITY_DECLARATIONS but had no entry in
PROVIDER_CAPABILITY_CONFORMANCE, so the conformance suite failed for it.
Name the existing Debian package CLI acceptance test as its case.

* fix(deb): flag repeated control and data members as extra

Only the first debian-binary, control.tar*, and data.tar* member is
read. A later member with the same role was neither decoded nor listed,
so a package with an empty first data.tar and a populated second one
reported complete coverage. Repeated members now land in
extra_member_names with a limitation, which keeps coverage partial.

* refactor(deb): use the shared excerpt and error message owners

The architecture guards from main count a hand-written ellipsis cut in
the relationship issue detail and two inline error-to-message copies.
Use ellipsisExcerpt and errorMessage instead.

* refactor(deb): move DebPackagePort to src/ports/deb

The provider imported its port from the application layer, which needed
an upward allowance in the module-layer baseline. Put the port beside the
other provider ports and drop the allowance.

* fix(deb): record only caller-selected budgets in Evidence

Omitted inspect_deb_package budgets no longer appear in Evidence
parameters as if the caller set them; only supplied fields are kept.

* fix(deb): report fixed reader allowances as limits

The ar member name, tar extension header, and relationship alternatives
allowances stop inspection without showing the input is invalid. Report
them as `limit` parse failures (DebPackageAllowanceFailure) with the
partial report attached, and project them as resource_constraint with a
fixed-allowance recovery instead of invalid_request.

* fix(deb): refuse GNU ar long name references outside the string table

A `/<offset>` reference past the end of the `//` string table, or one
that lands on an empty entry, resolved to an empty member name. The
report then failed debPackageSchema and callers got AnalysisOutputError
with no file identity or partial facts. Check the offset and the
resolved name, and refuse as a malformed DebPackageFormatFailure that
carries the partial report.

* fix(deb): align ar members by stored size and require padding

Advance past each ar member using the stored header size, so a BSD #1/N
extended name with odd length keeps the next header aligned. Refuse an
odd-sized member whose padding byte is missing at end of file instead of
reporting complete coverage for a truncated container.

* fix(deb): trim NUL-terminated header fields in linear time

Trim fixed-width ar and tar header fields at the first NUL with indexOf
instead of a NUL-to-end regex, which retried from every NUL when a
continuation line followed a NUL run. Control-field decimal parsing no
longer applies header NUL trimming.

* fix(deb): skip the tar path prefix on GNU headers

GNU tar headers use the 345-499 region for atime, ctime and sparse
data, not a POSIX path prefix. Only join the prefix when the header
carries the POSIX "ustar\0" magic.

* docs(readme): drop duplicated target tables in five translations

The fa, ko, th, zh-TW and zh guides carried the target table twice.
Restore each to upstream and add the single Debian packages row.

* fix(deb): report oversized Zstandard windows as a fixed allowance

A valid control or data zstd member can request a decoder window above
the fixed 128 MiB ceiling. Node raises
ZSTD_error_frameParameter_windowTooLarge, which the parser reported as
malformed. Map it to a DebPackageAllowanceFailure naming the new
zstd_window_bytes allowance, matching ZipArtifactReader.

* fix(package): bundle XZ decoder binaries for every plugin host

The plugin archive is produced on Linux x64, where npm ci drops other
platforms' optional packages. The packaging step only restored the PTY
binaries, so Codex plugin installs on macOS and Windows had no
@napi-rs/lzma binding and valid XZ packages failed as unsupported.

Derive the platform packages from the locked runtime tree instead:
every optional dependency of a runtime package that targets
darwin/linux/win32 on x64/arm64 is restored at its locked path with a
verified integrity, and the packed archive is checked for each one.

* fix(deb): keep only applied PAX keys while reading records

parsePax stored every record's key before PAX_KEYS filtered them, so one
extended header of many short records with distinct keys grew an object
property per record before any entry limit ran. Records whose key is not
one this reader applies are now read and dropped, and parsePax is covered
directly in DebPackageParser.test.ts.

* Address review feedback

* Trim deb822 lines with linear scans

The trailing-whitespace alternative of the shared trim expression retried
from every position of a long interior whitespace run, so a package
Description could take quadratic time. Scan from each end instead and
cover a long tab and space run in a test.

* fix(deb): read only the first control paragraph

parseControl used the first paragraph of the control file, but
deb822Paragraphs built a map for every paragraph first. A control file
of many small paragraphs could allocate millions of maps within the
decompressed-size budget. deb822Paragraphs now takes a paragraph limit
and yields string lines lazily, and parseControl stops after the first
paragraph.

* fix(deb): report unreadable tar modes as null

A tar header whose mode field is not octal was reported as mode 0000,
which invents a permission the archive never stated. Report the mode as
null and add a malformed issue for the member, so coverage is partial.

* fix(deb): refuse GNU sparse tar entries

GNU PAX sparse headers (GNU.sparse.*) rename the following entry to a
synthetic GNUSparseFile path and store only mapped segments, so reading
it as a regular file reported the wrong name and size and could miss
md5sums cross-checks. Old GNU sparse (S) entries can also carry
extension blocks their size field does not count. Refuse both as an
unsupported format instead of reporting wrong file facts.

* refactor: use shared artifact inspection for Debian packages

* fix(deb): report per-call budget refusals as parameter limits

* Address review feedback

* Address review feedback

* fix(deb): bound xz decoding, inherit global PAX size, and redact Homepage URLs

* fix(deb): bound xz index preflight memory and preserve typed cancellation with partial facts

* fix(deb): bound nested relationship lists, align tar stored-body rule, and scope async parse

* fix(deb): walk actual XZ block boundaries, scan control lines without arrays, and guard XZ close gate

* refactor(deb): avoid throwaway filter arrays in DebPackageParser

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Matt Van Horn <mvanhorn@MacBook-Pro-10.local>
2026-11-26 18:10:02 -05:00
2c89136469 feat(artifacts): inspect VS Code extension packages offline (#12469)
* feat(artifacts): inspect VS Code extension packages offline

REA had no owner for a local .vsix ZIP. inspect_vsix_package and inspect-vsix-package now read extension.vsixmanifest and extension/package.json, report identity disagreements, engine range, activation events, a contributes summary, hashed native/wasm/executable members, and a ZIP inventory without installing the extension or contacting a marketplace.

Missing or malformed manifests return the inventory with limitations. Invalid ZIP input fails without partial success. Signature files are reported present or absent and are not verified.

* fix(vsix): bound vsixmanifest XML nodes before building the tree

A compressed extension.vsixmanifest within the 16 MiB byte budget can
still expand into millions of XML nodes. Count nodes as a stream first,
as the Maven POM reader does, and refuse the manifest with an xml_nodes
limit before parseXmlDocument allocates its document.

* fix(vsix): report the vsixmanifest node ceiling as a fixed allowance

The xml_nodes limit is a fixed parser ceiling, not a caller budget, so
the provider fell through to a generic memory refusal that implied more
memory could help. Map it through fixedAllowanceOptions as the Maven
provider does and cover the public error from the provider.

* refactor(vsix): classify provider failures through the shared owner

VsixPackageProvider kept its own chain for cancellation, identity, path,
selected-file and cleanup failures. It now supplies a dialect to
classifyProviderFailure with only the package's own refusals: its parse
ceilings and budget recovery, format failures, fixed reader allowances and
the max_file_bytes refusal. The held snapshot still supplies the completed
identity for a parser failure after the read.

* fix(vsix): report an empty contributes key instead of failing the report

A package.json with an empty contributes key produced a key with an
empty name, which the contract refuses, so the whole inventory was
rejected. The empty key is now left out of contributes.keys and
reported as a limitation.

* fix(vsix): charge member decoding to one package-wide budget

Each hashed member was read with a fresh per-member budget, so a small
compressed package with thousands of members could make the parser
decode several GiB. Member reads now draw on one artifactExpansionBudgetBytes
budget for the package; once it is spent, remaining members stay in the
inventory without a digest and a limitation names the spent budget.

* fix(vsix): resolve dot segments in package.json entry points

packageJsonEntryPath stripped only one leading ./, so a main such as
./out/./extension.js named extension/out/./extension.js and was reported
absent even when extension/out/extension.js existed. Entry points now
resolve . and .. segments under extension/; a path that climbs out of
extension/ keeps its unresolved form and matches no member.

* fix(vsix): resolve entry points with the loader's lookup rules

An extension-less main such as ./out/extension was looked up as a
literal ZIP name and reported absent although Node resolves it to
extension/out/extension.js. main now tries Node's CommonJS file and
directory suffixes, browser tries the .js the web extension host adds,
and the reported path is the member found.

* fix(vsix): resolve a directory main through its own package.json

Node's directory lookup reads the directory's package.json main before
falling back to index files, so an entry like main: ./out with
out/package.json naming ./start.js now resolves as present.

* Address review feedback

* fix(vsix): report interesting member sizes past 4 GiB

A ZIP64 member can declare an uncompressed size above 0xffffffff while
the compressed package stays under max_file_bytes. The parser skips
hashing it and reports the declared size, but interesting_members[].bytes
used the 32-bit uint schema, so the service rejected the whole report.
The field now takes any nonnegative integer, matching
contents[].uncompressed_size.

* fix(vsix): report a malformed directory package.json instead of its index

When main names a directory whose package.json is not a JSON object,
Node's loader throws ERR_INVALID_PACKAGE_CONFIG rather than falling back
to index.js. Keep that outcome distinct from a manifest with no usable
main: mark the entry point absent and add a limitation naming the member.

* fix(vsix): classify Java archives as nested archives

A bundled .jar, .war or .ear is a ZIP, but the path classifier returned unknown for it, so it was never hashed or counted as a nested archive.

* fix(vsix): match entry points by exact member case

Resolve main and browser entry points against exact ZIP member names, as a
case-sensitive file system would, and report a member that matches only when
case is ignored as a limitation instead of marking the entry present. The
directory package.json used to resolve a directory main is matched exactly
too.

* fix(vsix): keep directory-only intent for a trailing-slash main

A main such as "./out/", ".", "..", or one ending in "/." or "/.." can
only name a directory under Node's loader. Normalizing it to a bare path
let a sibling file like extension/out.js match and report the entry as
present. Carry a directory-only flag from the raw value and skip file
candidates in the declared-path lookup and in the check that decides
whether to read <main>/package.json.

* fix(vsix): only blame case when the spelling differs

The case-only entry point warning scanned index candidates even when a
malformed directory package.json had already stopped the main lookup, so
an exact extension/out/index.js could be reported as a case mismatch.
Skip index candidates when the directory manifest is malformed, and skip
any candidate whose member is spelled exactly as declared.

* fix(vsix): stop main lookup at an over-budget directory package.json

When main names a directory whose package.json exceeds
max_manifest_bytes, its main is unknown, so falling back to index.*
could report a file Node would not load. Treat the unread manifest like
a malformed one: report main unresolved, add a limitation that says the
index files were not used, and skip the index files in the case-only
scan.

* fix(vsix): resolve a main that normalizes to the package root

A main of ".", "./" or "./out/.." normalized to "extension/", so the
directory lookups searched "extension//package.json" and
"extension//index.js" and reported a present index file as absent.
Return "extension" for the root so those lookups name real members.

* fix(vsix): stop main lookup at an unread directory package.json

An encrypted or duplicated directory package.json left the directory
main unresolved as "none", so lookup fell through to index files even
though the unread manifest may name another file or be invalid. Mark it
unread and stop the lookup, as the over-budget branch already does.

* test(vsix): tag the decode-budget regression long-running

The package-wide decode budget test passed a fixed 60-second deadline,
which also turned off coverage and CI deadline scaling. Use the
long-running tag the testing guide prescribes instead.

* fix(vsix): leave unread dependency declarations unknown

A missing, encrypted, or malformed manifest reported its extension
dependencies and extension pack as empty lists, so a declaration on the
other side showed up as a disagreement. Report the unread side as null
and only flag a disagreement when both manifests were read.

* fix(vsix): look up entry points by their literal text

package.json main, browser, and a directory package.json main were
trimmed before lookup. A ZIP member name can begin or end with
whitespace and Node does not trim the specifier, so "./out/start.js "
was reported absent or matched the different "out/start.js" member.
Use the declared text as written; only an empty string names nothing.

* fix(vsix): keep activation events literal before eager classification

VS Code matches activation events as exact strings, so "* " and
"onStartupFinished " are not startup activations. The parser read
activationEvents through the whitespace-trimming ID helper, which turned
those values into "*" and "onStartupFinished" and reported them as eager.

Read activation events with a literal helper that drops only empty
strings and exact duplicates, and cover the padded values next to their
exact-name controls.

* fix(vsix): keep mode-executable members inventoried when unread

A member with no recognized suffix but Unix execute bits was only
classified after its magic was read. When the hash budget, the package
decode budget, encryption, or traversal skipped that read, it stayed
unknown and fell out of interesting_members and the executable count.
Unread mode-executable members now keep an inferred executable kind.

* fix(vsix): count a singleton contributes.commands object

VS Code accepts contributes.commands as one command object as well as
an array. Normalize the singleton form before capping and counting so a
package with one command reports commands_total 1 and the commands key
count matches.

* fix(vsix): keep contributed command identifiers literal

VS Code registers and invokes a contributed command by its exact
identifier, and the parser already keeps onCommand activation events
literal. Commands went through the trimming text helper, so a declared
"demo.run " was reported as "demo.run" next to an "onCommand:demo.run "
event, giving two different identities for the same command.

Keep the declared command text as written and report null only for an
empty string. Titles are display text and stay trimmed.

* fix(vsix): do not infer executables from symlink modes

A Unix symlink entry carries 0o120777, so its permission bits made an
unread link look like an executable helper. Only regular files, or
entries with no recorded file type, now count toward mode-inferred
executables.

* style(vsix): apply oxfmt to manifest limit guard

* fix(vsix): keep mode-executable kind when read bytes have no known magic

A suffixless regular Unix member with execute bits but no recognized
magic (for example a shell helper without a shebang) was listed as an
executable only when the hash budget skipped its read. Raising the
budget enough to hash it resolved the kind to unknown and dropped it
from interesting_members and the executable count. Fall back to the
mode-derived executable kind when the read bytes match no magic.

* fix(vsix): charge failed member expansions to the package budget

A member whose ZIP header understates its uncompressed size can decode
its whole allowance before the bounded writer refuses it. That work was
not charged to the package-wide decode budget, so every later failing
member got the same allowance again. Charge the allowance on a
max_member_bytes failure so later members see the spent budget.

* fix(vsix): bound JSON values before parsing manifests

Both package.json readers called JSON.parse after a byte-only check, so a
16 MiB manifest of many tiny values could allocate far more memory than its
text. A one-pass countJsonValues scan now runs first: an extension/package.json
holding more than 1,048,576 values is refused with a fixed json_values parser
allowance, and an over-allowance directory package.json is left unread with a
limitation, so its index files are not used.

* Address review feedback

* fix(vsix): treat absolute directory package.json main as outside the package

Node resolves a directory package main with path.resolve(dir, main), so an
absolute main names a host file, never a package member. Report it as no
main so the lookup falls back to index.* or reports the entry absent.

* fix(vsix): tag escaped entry points instead of matching them as members

A package.json main or browser that climbs out of extension/ was kept as
an ordinary member path string. A traversal ZIP member with the same name
(extension/../outside.js) is in the inventory, so the lookup reported the
entry point present even though that member is never extracted.

packageJsonEntryPath now returns a tagged resolved/escaped value. Escaped
entry points skip the member, directory manifest and case-only lookups and
are reported with present: false.

* fix(vsix): decode directory package.json as UTF-8 like Node

Node reads a nested package.json as UTF-8 only. A UTF-16 manifest
fails with ERR_INVALID_PACKAGE_CONFIG, so report it malformed instead
of transcoding it and marking main present.

* fix(vsix): keep directory package.json main inside the extension root

A directory package.json main such as ../../outside.js could pop the
extension segment and resolve to an archive-root member, which was then
reported as the present main entry point. Treat any main that climbs out
of extension/ as naming no main, so the lookup falls back to index.* or
reports the entry absent.

* fix(vsix): keep a root directory main from matching archive-root files

A nested package.json main such as ".." in extension/out resolves to the
extension root itself. Trying file suffixes on that path matched an
archive-root extension.js, which sits outside the installed payload.
Mark such a main directoryOnly and resolve it through extension/index.*
only, as Node does.

* fix(vsix): skip member reads once the package decode budget is spent

A compressed member declaring zero uncompressed bytes passed the
declared-size check even with no package allowance left, so its decoder
still ran and produced output before the writer rejected it. The failure
then charged zero, letting each later zero-declared member decompress
again past the package ceiling. Skip the read and report the spent
budget once nothing remains.

* fix(vsix): keep declared API proposal names literal

Read enabledApiProposals with the literal list reader used for activation
events. VS Code matches proposal names exactly, so trimming whitespace or
splitting on commas reported identifiers the package never declared and
collapsed declarations that differ only in surrounding whitespace.

* fix(vsix): select manifests by their exact member path

Count ZIP members by exact logical path. A package holding only
extension/Package.json no longer has it parsed as extension/package.json,
and a case-only sibling no longer marks the real lowercase manifest as a
duplicate and drops its facts. Names that differ only in case, and a
manifest present only under another case, are reported as their own
limitations.

* fix(vsix): treat shared libraries as interesting members

Bundled .dll, .so (including versioned .so.N names) and .dylib files
without Unix execute bits were classified unknown, so their magic was
never read and they were missing from interesting_members and the
summary count. Classify these suffixes as executable so they are hashed
and listed like .exe and .node members.

* refactor(vsix): run inspection through the shared artifact runner

VsixPackageService now delegates input parsing, the provider call, output
checks, Evidence creation and late cancellation to executeArtifactInspection,
as NugetNupkgService does, keeping only the VSIX-specific report checks.

* feat(vsix): point first-contact inspection of a .vsix to the VSIX reader

inspect_artifact now suggests inspect_vsix_package when a ZIP holds a
root extension.vsixmanifest file. The non-ZIP refusal test follows main's
unsupported_target classification for malformed target bytes.

* fix(vsix): align artifact failures with main

* fix(vsix): bound inspect_vsix_package output with shared detail/summary contract

* Address review feedback

* fix(vsix): bound summary text fields and report structured parameter limits

* fix(vsix): omit required_value on early-stop parameter limits

* refactor(vsix): count eager activation events without intermediate array

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Matt Van Horn <mvanhorn@MacBook-Pro-10.local>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-26 22:03:28 +00:00
6a6e7b0bbf feat(artifacts): inventory OCI image layouts offline (#12470)
* feat(artifacts): inventory OCI image layouts offline

OCI image-layout directories (oci-layout, index.json, blobs/) arrive as evidence and previously required walking the JSON by hand.

This adds inspect_oci_image_layout / inspect-oci-image-layout for the directory form only. It reports layout version, nested indexes, image config facts, layers, and streamed SHA-256 (and SHA-512 when declared) verification of present referenced blobs. Env values stay omitted unless include_env_values is selected. Missing blobs, digest and size mismatches, unreferenced blobs, unknown media types, unsupported digest algorithms, and symlink blobs are findings. Layer contents are not decompressed.

* fix(oci): preserve whitespace in image config strings

Keep config facts such as WorkingDir exactly as written instead of
returning their trimmed form. Blank values still count as absent.

* fix(oci): read the platform os.version member

The OCI image index stores a platform version under the literal
"os.version" member, so Windows entries that share OS and architecture
keep the build that tells them apart.

* fix(oci): keep config Env values unless the caller omits them

Env values are bytes from the selected image, and AGENTS.md asks to
preserve local evidence without inferring secrecy from names. The
include_env_values control now defaults to true; false still leaves each
value null and keeps the names.

* fix(oci): report descriptors the parser cannot model

An index, layer or config descriptor without a string mediaType or digest
was dropped with no diagnostic, so an index of only malformed descriptors
read as an empty, fully covered index. Each such descriptor now records a
malformed_blob_json finding naming its position, what it lacks and any
digest it carries.

* fix(oci): walk nested indexes breadth-first

The index walk was depth-first with a visited set that ignored depth, so
an index shared between a nested path and the root was first visited too
deep, and what it reached within max_index_depth was never inventoried.
Indexes now queue breadth-first, so each is first reached at the
shallowest depth any path gives it.

* fix(oci): check every declared size of a shared blob

When several descriptors referenced one blob with different sizes,
remember kept only the first declaration, so a wrong later size was
never checked. Each referenced blob now keeps every distinct declared
size, and the file-size and hashed-byte checks run against each one.

* fix(oci): report partial coverage when referenced JSON is not read

A referenced index, manifest or config that was a symlink, or otherwise
could not be read, left its facts unexamined while coverage still read
complete. Any skipped referenced JSON read now makes coverage partial,
whatever finding explains it.

* fix(oci): report unsupported layer digests without calling them missing

A layer whose digest used an unsupported algorithm got no finding and
was recorded as a missing blob, even when its file existed, and coverage
could read complete. Every referenced digest with an unsupported
algorithm now records unsupported_digest_algorithm, its blob record
reflects the file at blobs/<algorithm>/<encoded>, and such a finding
makes coverage partial.

* fix(oci): keep the parse outcome when reader cleanup fails

The provider's finally replaced the parse result with a cleanup failure
that always claimed the parse completed, so a refusal, cancellation or
integrity failure and its layout snapshot were lost when closing the
reader also failed. The parse outcome is now captured first; a failed
parse stays the primary error, with its partial facts, and the cleanup
failure is attached to it.

* Address review feedback

* fix(oci): keep oci-layout snapshot on missing imageLayoutVersion

Build the oci-layout file snapshot before checking imageLayoutVersion and
attach it to the refusal, so a readable oci-layout without a version still
reports its sha256 and byte count.

* fix(oci): keep directory traversal coverage in layout reports

parseOciImageLayout iterated the directory reader without an onCoverage
sink, so names the reader skipped (for example non-UTF-8 names on Linux)
left the report claiming complete coverage with no limitation. Collect
the traversal coverage, carry its limitations into the report, and let
unknown or partial traversal coverage override the findings-based status.
A reader that reports nothing is treated as unknown.

* fix(oci): keep reader failures on referenced blobs

A referenced index, manifest or config read that failed in the reader,
for example a close failure after the JSON was fully read, was recorded
as malformed_blob_json and the call carried on. Only format failures
become findings now; reader failures reach the caller with their own
facts.

* fix(oci): budget decoded descriptors separately from directory entries

max_entries bounds the directory walk, but index, manifest and layer
descriptors also spent it, so many manifests sharing layers were refused
far inside the advertised directory budget. Decoded descriptors now spend
their own max_descriptors allowance (default 65536, maximum 1048576), and
a refusal names that allowance.

* fix(oci): keep the completed inventory when reader cleanup fails

When parsing finished but closing the directory reader failed, the
provider threw a cleanup failure built against a placeholder outcome and
the completed inventory was dropped. The cleanup failure now carries the
completed report as unretained Evidence in its partial observation, the
same way DesktopApplicationReader keeps its report. A provider test
covers that case and checks that a later close retries the failed
reader cleanup.

* fix(oci): keep reader omissions out of complete layout coverage

parseOciImageLayout took the directory reader's coverage but not its
omission callback, so a FIFO, socket or device node under blobs/ was
dropped from the blob inventory while the report still said complete.
Collect omissions other than the intentional skip of directories
outside blobs/, name the first one in a limitation, and report unknown
coverage when any were seen.

* refactor(oci): classify layout failures through classifyProviderFailure

The provider kept its own raw-error ladder in layoutFailure. Its OCI
decisions (unsupported root or symlink, parse limits with budget
recovery, format failures, reader failures) are now the recognise step
of a ProviderFailureDialect, with the io report as its unclassified
fallback, so typed failures pass through, cancelled reads use the shared
cancellation path, and a failed read's cleanup is bound by the shared
owner.

* fix(oci): match referenced blobs by resolved path

parseOciDigest accepts uppercase SHA-256 hex and resolves it to the
lowercase blob path, but the unreferenced-blob sweep keyed membership by
the descriptor's original spelling. A blob named that way was hashed as
referenced and also reported as unreferenced_blob with a second
referenced: false row. Track the resolved paths of referenced blobs and
skip them in the sweep.

* fix(oci): read shared configs once and budget expanded config facts

Each manifest reread and reparsed its config, and every image carried its
own copy of the facts, so many small manifests sharing a large config
could expand to far more memory than the per-file limits suggest before
the service checked the report.

Each config blob is now read and parsed once per layout and its facts are
reused. The config bytes behind each image spend a new max_config_bytes
allowance (default 64 MiB, maximum 512 MiB) before the image is added, so
a shared config counts once per image and an expansion past the budget
refuses the inspect and names that allowance.

* fix(oci): report blob sizes above 4 GiB

Descriptor, layer and blob sizes used the 32-bit count schema, so a
layout with a blob over 4 GiB produced a report the output schema
rejected, hiding its blob_oversize finding. Sizes now accept any
nonnegative safe integer; depth and coverage counts stay 32-bit.

* fix(oci): report a referenced layer that is not a regular file

A referenced layer whose blob path is a directory was recorded as kind
other with present false, but no finding was emitted. Layer blobs never
go through the referenced JSON reader, so coverage stayed complete even
though the layer was never verified. The layer now gets a missing_blob
finding, matching non-file indexes, manifests and configs, and coverage
is reported as partial.

* fix(oci): keep the oci-layout hash when a later budget refuses

A manifest or config past max_json_bytes, or a layout past
max_descriptors or max_config_bytes, threw a bare ParseFailureError
after oci-layout had been read and hashed. The provider only attaches
partial facts to OciImageLayoutRefusal, so that completed observation
was dropped.

The parser now rewraps any later ParseFailureError as an
OciImageLayoutRefusal carrying the oci-layout snapshot, so every
refusal after that point reports it as the partial observation.

* fix(oci): keep blobs unknown when the reference walk is truncated

When max_index_depth, an unreadable index or manifest, or a descriptor
that cannot be modeled stops the reference walk, blobs outside the
walked part were reported as unreferenced_blob. They may still be
reachable from what was not examined, so the parser now only asserts
unreferenced status after a complete walk and otherwise records a
limitation and leaves those blobs out of the inventory.

* fix(oci): report wrong-typed manifests and layers arrays

A non-array manifests member in index.json now refuses the layout and
keeps the oci-layout observation. A non-array manifests member in a
nested index, or a non-array layers member in a manifest, records a
malformed_blob_json finding and marks the reference graph truncated
instead of reading as an empty collection.

* fix(oci): report image configs whose root is not a JSON object

A config blob holding valid JSON such as [] or null fell back to empty
facts with no finding, so the report claimed complete coverage. Record a
malformed_blob_json finding for the config digest while keeping the
manifest and layer observations.

* fix(oci): decode only image config media types as JSON

A manifest whose config is application/octet-stream or another
non-image type no longer has its config run through the JSON decoder.
Valid binary config bytes produced a false malformed_blob_json finding,
and a config larger than max_json_bytes refused the whole inventory even
when it fit max_blob_bytes. Such configs now stay opaque references that
the blob pass hashes; the unknown_media_type finding is kept.

* fix(oci): bound JSON reads by the descriptor budget

The service checked json_bytes_read against one max_json_bytes document
per returned index and image plus two. A layout reads a manifest and a
config per image, and manifests or nested indexes that fail to parse are
read without appearing in the report, so valid layouts whose every
document fit max_json_bytes could be rejected after parsing.

Every nested index or manifest read is charged one descriptor and each
manifest reads at most one config, so bound the total by oci-layout,
index.json and two documents per allowed descriptor.

* fix(oci): count OCI 1.1 subject blobs as referenced

A manifest or index subject that names a blob present in the layout now
joins the referenced set, so the blob is hashed and is not reported as
unreferenced. A subject absent from the layout is allowed by the spec
and adds no finding. A subject that is not a descriptor is reported as
malformed and keeps unreferenced blobs unknown.

* fix(oci): keep caller selections in cleanup-recovered Evidence

When the reader fails to close after a completed inspection, the provider
keeps the inventory as partial Evidence built from the resolved input, so
its parameters named defaults the caller never chose and its Evidence ID
differed from the success path. Build both from one OCI Evidence helper
and have the service rebuild a recovered inventory from the caller's own
selections.

* fix(oci): keep blob rows when the reference graph walk is incomplete

When a nested index or manifest could not be read or exceeded
max_index_depth, every blob outside the walked part was dropped from the
report, losing its path, size and kind. List those blobs with a null
referenced status instead, and report unreferenced_blob only when the
whole graph was examined.

* fix(oci): report unknown media types on present subjects

A subject blob present in the layout now joins the referenced set, which
removed its unreferenced_blob finding. Index entries, layers and configs
also report an unfamiliar media type, but subjects skipped that check, so
an unknown subject format went unreported. A present subject with an
unknown media type now records unknown_media_type.

* perf(oci): index emitted blob findings instead of rescanning them

The blob inventory loop checked each referenced digest against the whole
findings array before recording missing_blob, symlink_blob, or
unsupported_digest_algorithm, which is quadratic for layouts with many
missing blobs. Index finding kind and digest in a set built once before
the loop so each check is constant time. Output is unchanged.

* fix(oci): report invalid descriptor sizes as malformed

An index entry, config, layer or subject descriptor whose required size
was missing, a string, negative or fractional became a null size, which
dropped it from size validation without any finding, so the report could
claim complete coverage. The descriptor still keeps its other facts, but
the defect is now recorded as malformed_blob_json on the owning blob.

* fix(oci): keep damaged config, subject and descriptor facts in the report

Image config parsing kept any string in rootfs.diff_ids, so a readable
config with diff_ids [""] produced output the schema rejects and the
service discarded the whole inventory as an AnalysisOutputError. Config
parsing now owns that boundary: diff_ids members that are not nonempty
strings, and empty ExposedPorts or Volumes keys, are omitted and reported
once per config blob as malformed_blob_json, and the manifest and layer
observations stay in the report.

Related gaps in the same walk:

- A present subject was hashed but never walked, so blobs it names were
  reported as unreferenced. A subject manifest now goes through
  walkManifest and a subject index joins the breadth-first index queue one
  level below its owner, within max_index_depth.
- A manifest with no config member reported complete coverage. A missing
  config is now treated like a malformed one.
- A symlinked referenced blob was not hashed but left coverage complete.
  symlink_blob now makes coverage partial.
- An unusable descriptor size was serialized into the finding message.
  It is now described by type and length, with short strings quoted.
- A reader failure after oci-layout was hashed dropped that observation.
  It is now attached when the reader did not attach its own.
- Annotation and label names allowed by OCI, including the empty key,
  failed the output schema. The name is now any string. The advertised
  compact output schema summary is unchanged.

* perf(oci): index declared sizes for shared blobs

Recording a distinct declared size scanned every earlier declaration for
the same blob, so many references to one blob with distinct sizes cost
quadratic work inside max_descriptors. ReferencedBlob now keeps a Set
beside declaredSizes for membership, and the array keeps declaration order
for verification.

* fix(oci): walk subject manifests from a queue

Finish each manifest before reading the one its local subject names, so a
long subject chain no longer keeps every parsed document alive at once.

* fix(oci): resolve unsupported-digest layer presence at its layout path

A layer stored at blobs/sha1/<hex> was reported present: false because
the layer lookup only resolved verifiable digests, while the blob
inventory reported the same file present. Use the grammar-based path
fallback for layer presence too.

* fix(oci): keep reference coverage uncertain for opaque index entries

An index entry with an unknown media type is not walked, so the blobs
it references are unknown. Mark the reference graph truncated so no
blob is reported unreferenced, and report coverage as partial whenever
the reference graph was not fully examined.

* fix(oci): walk digest aliases that differ only in hex casing once

Descriptors whose digests differ only in accepted hex casing resolve to
one blob, but the index queue, visited set and config cache were keyed
by the source spelling, so each alias reread and rewalked the whole
index. Key traversal by the resolved blob path while descriptors keep
their source spelling in the report.

* fix(oci): keep unparsed digest spellings out of accepted traversal keys

A descriptor spelled blobs/sha256/<hex> did not parse, so its traversal
key fell back to the raw text, which matched the blob path key of the
accepted sha256:<hex> digest. Listed first, it marked the manifest
visited and the valid descriptor was skipped. Prefix accepted and
unparsed keys separately.

* fix(oci): bound index entry text retained across indexes

Index entries keep their digests, media types, platforms and annotations
in the report, but no allowance covered that text across indexes, so many
nested indexes with large annotations could exhaust memory within every
other limit. Charge each retained entry to a new max_descriptor_bytes
budget (64 MiB default, 512 MiB maximum) before adding it.

* fix(oci): hash each blob file once across digest spellings

Digest spellings that differ only in accepted hex casing resolve to one
blob path, but the blob pass hashed the file once per spelling. Cache the
hash result, or its oversize refusal, by blob path so each file is read
once, while every spelling keeps its own row, size checks and digest
check.

* fix(oci): report non-object config and rootfs subobjects

A present config or rootfs value that is not a JSON object now records a
malformed_blob_json defect instead of being replaced by an empty object, so
coverage reports partial. Other image facts are kept. Regenerate the
inspect_oci_image_layout advertised-schema summary.

* fix(oci): check declared sizes for unsupported-digest blobs

A blob referenced by a valid but unsupported digest (for example sha1)
skipped the declared-size checks and left observed_size null, even
though the directory reader already captured the file size. Record
observed_size and emit size_mismatch for it, still without hashing.

* fix(oci): keep reader integrity failures that wrap a JSON parse failure

readJsonDocument unwrapped any ArtifactReaderFailure whose cause was a
ParseFailureError. When a malformed referenced blob changed during
inspection, DirectoryArtifactReader.inspectFile raised an "integrity"
failure carrying that ParseFailureError, and the unwrap turned it back
into a malformed_blob_json finding. Only unwrap the plain "io" transport
wrapper with no cleanup lease, so integrity, cancelled and limit
failures keep their reader facts.

* fix(oci): report malformed config leaf fields

A config with Env: "A=1" or Cmd: ["/bin/sh", false] used to come back
as env: [] or cmd: null with no finding, indistinguishable from an
image that declared neither. parseConfig now checks each present known
field (the top-level strings, User, Env, Entrypoint, Cmd, WorkingDir,
ExposedPorts, Volumes, Labels, StopSignal) and records
malformed_blob_json for a wrong type, keeping the other facts. Env
members that are not a named string and non-string label values are
omitted and counted. null stays an omitted declaration.

* fix(oci): allow json_bytes_read beyond 32 bits

coverage.json_bytes_read sums bytes across every JSON document read.
OciImageLayoutService bounds it by max_json_bytes * (2 + 2 *
max_descriptors), which at a 16 MiB per-document cap passes 0xffffffff
well within budget, so the uint schema made safeParse reject a completed
report as AnalysisOutputError. Give the counter a nonnegative safe-integer
schema; the other uint counters are unchanged.

* fix(oci): report malformed image history

A non-array history or a history member that is not an object was
silently dropped, so damaged build history looked the same as omitted
history. Report both as malformed_blob_json defects on the config blob
and keep the readable history records and other image facts.

* fix(oci): report damaged descriptor metadata and symlinked blob dirs

Descriptor platform and annotations that were present but malformed
(platform: [], a non-string platform field, annotations that are not an
object or hold non-string values) were normalized to null or [] with no
finding. Report each as a malformed_blob_json defect against the owning
document and keep the readable entries.

A symlink at blobs or blobs/<algorithm> is not followed, but nothing
recorded the skipped tree, so an empty index over a linked blob
directory reported an empty inventory with complete coverage. Record a
symlink_blob finding for the linked directory so coverage is partial.

* Address review feedback

* Address review feedback

* Address review feedback

* Bound repeated JSON member names in OCI findings

A long duplicate member name is now described by its length instead of
being copied into the finding message.

* fix(oci): keep the oci-layout hash when its JSON is malformed

The oci-layout file is now read and hashed first, and its observation is
recorded before decoding. An oci-layout with invalid UTF-8, invalid JSON
or a duplicate member is refused with its completed file identity.

* fix(oci): charge accepted descriptor text to max_descriptor_bytes

Accepted subject, config and layer descriptors keep their digest and
media type in image rows, the reference map, findings and blob rows, but
only index entries and rejected descriptors spent max_descriptor_bytes.
A layout with many manifests carrying long distinct layer digests could
retain unbounded text. Charge accepted descriptor text before retaining
it, once per referencing manifest or index.

* fix(oci): report presence defects for unsupported-digest blobs

A referenced blob with an unsupported digest algorithm whose layout path
is missing, a symlink, or not a regular file now gets the same
missing_blob or symlink_blob finding a supported digest gets, alongside
unsupported_digest_algorithm. Present files still only get the size
check and stay non-missing.

* perf(oci): drain index and manifest queues with a cursor

shift() relocates the remaining queue on every step, which makes draining
layouts with many index references quadratic. Walk both breadth-first
queues with an index cursor instead.

* fix(oci): keep blobs under a symlinked blob directory unexamined

When blobs or blobs/<algorithm> is a symlink, the reader lists the link
but never its children, so a referenced blob under it is absent from the
listing without being absent from the layout. One shared lookup now
tells listed, unexamined and confirmed-missing paths apart for the
reference walk, subjects, and both inventory branches. An unexamined
blob gets a symlink_blob finding naming the directory instead of
missing_blob, and an unexamined subject marks the reference graph
truncated.

* fix(oci): charge serialized config facts to max_config_bytes

The config allowance counted the config document's source bytes, but each
image carries the parsed facts, and a sparse history entry such as {}
expands into a record with four null fields. A small shared config with
thousands of empty history entries could pass the budget while the report
grew past the runtime's string limit. Each distinct config now charges the
exact compact JSON size of its facts, once per image that uses it.

* fix(oci): keep the oci-layout snapshot when its read fails to finalize

When the oci-layout read completes but closing its descriptor fails, or
cancellation arrives during the close, the reader rejects before the
parser records the layout hash. The reader keeps the completed bytes on
that failure, so the failure reached translation without the SHA-256 and
byte count it could have carried, unlike the same failure on index.json.
The parser now records the completed layout observation from that outcome
and rethrows the reader's failure unchanged, keeping its cleanup owner.

* fix(oci): keep reference status unknown under an unwalked present subject

A present subject with an unknown media type, or an index or manifest
subject whose digest algorithm is unsupported, is not read, so the blobs
it names were reported as unreferenced with complete coverage. Mark the
reference graph truncated in both cases so unmatched blobs keep an
unknown referenced status.

* fix(oci): keep a malformed index.json primary when its handle close fails

When index.json is malformed and closing its descriptor also fails, the
directory reader raises ArtifactFileCleanupFailure with reason io and keeps
the ParseFailureError as the physical outcome. The OCI dialect translated
the wrapper directly, so the malformed input surfaced as an I/O failure even
after the resource scope retried the close.

The dialect now supplies readCleanup: the shared classifier classifies the
failed outcome as primary, and the unresolved close is attached beside it
and bound to that read's exact cleanup lease. A cleanup-only read keeps its
previous projection.

* fix(oci): count a malformed blob's bytes in json_bytes_read

A referenced index, manifest or config that was read in full but failed
UTF-8, JSON or duplicate-member decoding became a malformed_blob_json
finding, yet its bytes never reached json_bytes_read, because the count
was added only after decoding succeeded.

The blob read now adds the byte count inside the completed read, before
decoding, so coverage reports every byte the parser examined.

* fix(oci): report a missing or non-directory-ancestor path as invalid input

A selected root that resolves to ENOENT or ENOTDIR is a bad path, not an
I/O failure. Classify it as an AnalysisInputError on `path` before the
generic reader translation; other root I/O keeps its execution failure.

* fix(oci): keep the layout hash when index.json close also fails

When malformed index.json also failed to close, readCleanup composed the
error from the classified parse failure, which carries no observation,
so the completed oci-layout hash was dropped. Carry the read's partial
observation onto the primary before composing.

The close-fault test now selects the index.json handle by file identity
(dev and inode) rather than the second close call, and asserts the
fault landed there and the oci-layout hash survived.

* fix(oci): report malformed subject digests and count examined entries

A subject whose digest is not a valid OCI digest has no layout path, so
the walk returned without a finding and kept claiming it could prove
which blobs nothing references. It now records a malformed_blob_json
finding on the owner and marks the reference graph truncated, the same
as any other subject descriptor it cannot model. An absent subject with
a well-formed digest stays finding-free.

coverage.entries_examined counted only the entries the reader yielded.
It now takes the reader's examinedEntries from onCoverage, which
includes names the reader examined but omitted, and falls back to the
yielded count when the reader does not report one. An omission that
rewrites the traversal coverage keeps that count.

* fix(oci): keep the root index out of the blob traversal namespace

The root index was walked and prequeued under the traversal key of its
SHA-256 digest, which is the key of the blob path blobs/sha256/<hex>.
When a damaged nested index named that digest and the blob file there
held different index JSON, the queue skipped the blob as already walked,
so its manifests, configs and layers were never read and were reported
as unreferenced under complete coverage.

index.json now walks under its own traversal identity. A descriptor that
names its digest reads and walks the blob stored at that path like any
other nested index.

* fix(oci): diagnose conflicting media types inside referenced JSON

A referenced manifest or nested index may repeat its media type in its
own optional mediaType member. The walk ignored that declaration, so a
document admitted as a manifest but declaring the index type, or an
unknown type, produced no finding.

Check a present declaration against the descriptor type the walk
admitted it under. An unknown declared type is reported as
unknown_media_type; a known but conflicting type or a non-string value
is reported as malformed_blob_json. The members are still read, so the
other readable facts are kept, and an omitted mediaType stays valid.
The root index.json is admitted under its own declaration and is not
checked against itself.

* fix(oci): charge unknown declared media types to max_descriptor_bytes

A referenced manifest or nested index whose own mediaType is an unknown
string is quoted in an unknown_media_type finding. That text was retained
without spending the descriptor text budget, so many hash-valid documents
with long declarations could grow findings well past max_descriptor_bytes.
Charge the escaped declaration before the finding is recorded.

* fix(oci): mark the reference graph incomplete on document-type conflicts

A referenced manifest or nested index whose own mediaType names another
document kind, or an unknown type, was diagnosed but its blobs were still
judged with a complete reference graph. The walker reads only the members
of the admitted kind, so members of the declared kind, such as an index's
manifests inside a document admitted as a manifest, were never followed
and the blobs they name were reported as unreferenced_blob.

Mark the reference graph truncated for an unknown declared type or one of
a different document kind, so unreached blobs keep an unknown referenced
status. The readable facts are still reported. A declaration of the same
kind, such as the Docker manifest type on an OCI manifest descriptor,
reads the same members and keeps unreferenced status definite.

* docs(oci): state that unsupported digest algorithms skip hashing

The guide said every present referenced blob gets a SHA-256. Blobs whose
digest uses an algorithm other than sha256 or sha512 are not hashed; their
row reports hashed: false with null sha256 and sha512. Document that and pin
the null hash fields in the sha1 layer test.

* fix(oci): check the root index.json mediaType against the index kind

The root index.json skipped declaration checking because no descriptor
names it, so its own mediaType chose the admitted type. A root that
declared the manifest type or an unknown type was still walked as an
index with a complete reference graph, and blobs named by members the
index walk never reads were reported as unreferenced_blob.

Admit the root as an index: an index declaration of either family
stands, and any other declaration is checked against the OCI index type
like a nested index, which diagnoses it and marks the graph incomplete.

Also document that unknown declared media types quoted in findings
spend max_descriptor_bytes.

* Address review feedback

* Address review feedback

* fix(oci): check each referencing media type against a revisited document

A manifest or nested index reached a second time was skipped before its
mediaType declaration was compared with the new descriptor type, so a
conflict was reported or not depending on descriptor order. Each document
now records its declaration on first decode, and every distinct media type
a later reference admits it under is checked against it.

* fix(oci): detach redacted Env names from their bindings

With include_env_values false, each retained Env name was a slice of the
whole NAME=value string, so a long value stayed alive while the config
fact budget charged only the name. Redacted names are now standalone
copies, and a heap regression test covers eight 0.9 MiB values.

* fix(oci): keep only string mediaType declarations for revisit checks

The revisit cache kept each decoded document's raw mediaType, so a layout
of many manifests with large object declarations held all of them for the
whole walk while no byte budget charged them. A non-string declaration is
rejected whatever it holds, so the cache now keeps null in its place and
still reports it as not a string on each new referencing media type.

* Address review feedback

* Address review feedback

* Address review feedback

* fix(oci): preserve layout evidence on malformed targets

* Address review feedback

* fix(oci): diagnose schema versions and charge annotation records

Indexes and manifests whose schemaVersion is omitted, not a number, or a
number other than 2 now get a malformed_blob_json finding and partial
coverage, while their entries, config and layers stay readable.

Index entry annotations now spend max_descriptor_bytes as each
{name, value} record is built, charged at its serialized size, so many
short or empty annotations can no longer retain far more than their text
was charged for.

* docs(oci): describe annotation record accounting for max_descriptor_bytes

* Address review feedback

* fix(oci): wire summary delivery, parameter budget limits, and single-pass annotation parsing

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Matt Van Horn <mvanhorn@MacBook-Pro-10.local>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-26 20:02:44 +00:00
Matt Van Hornandgensokyo-dev 43b9fa87fb feat(artifacts): inspect NuGet package metadata and dependencies
Inspect supplied NuGet packages as local Evidence with bounded ZIP parsing, preserved caller choices and credential-safe metadata.

Fixes #8144

Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-17 13:13:02 +00:00
morluto af0db09605 refactor(resources): move the directory artifact reader into src/resources (#11520) 2026-11-16 07:32:08 +08:00
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
2026-11-16 07:05:30 +08:00
morluto cef87c498a refactor(architecture): add the ports and resources layers, move ports and shared resource owners there, and ratchet the layer baseline (#11208)
* test(architecture): fail on a stale layer baseline and document the declared layers

verify:module-boundaries reported a layer baseline entry whose imports were
gone but still passed, so main kept process -> artifacts at 20 after it fell
to 17 and a later change could add three imports back unnoticed. A stale
entry now fails like growth; --shrink-layer-baseline lowers it in the change
that removes the imports. The architecture map and CONTRIBUTING name
scripts/lib/module-layers.mjs as the per-directory layer declaration.

* test(architecture): refuse to lower the layer baseline after an inspection failure

A file that cannot be parsed contributes no imports, so a shrink run would record counts that fail as growth once the file is fixed. Whole-command tests cover stale rejection, shrinking, refused growth and the inspection failure.

* refactor(ports): move the progress, work-scope and inspection-scope ports to src/ports (#11214)

* refactor(ports): move the progress, work-scope and inspection-scope ports to src/ports

Pure move with git mv and import specifier updates.

* test(architecture): declare the ports layer and lower the layer baseline

src/ports sits between the foundation and the providers. Moving the three
ports removes 11 provider -> application imports.

* refactor(ports): move AnalysisProvider to src/ports (#11217)

* refactor(ports): move AnalysisProvider to src/ports

Pure move with git mv and import specifier updates in its importers, the
built-fixture path, the CI scope glob and the lint-rule test spellings.

* test(architecture): lower the layer baseline after moving AnalysisProvider

* refactor(ports): move the per-feature provider ports to src/ports (#11226)

* refactor(ports): move the per-feature provider ports to src/ports

Pure move with git mv and import specifier updates: the 47 *Port.ts and
*Ports.ts files that providers implement, plus OptionalObservationProviders,
which only composes the observation ports.

* test(architecture): lower the layer baseline after moving the feature ports

* refactor(providers): move closeAnalysisClient and the Frida session input errors to their owners (#11233)

* refactor(providers): move closeAnalysisClient to src/providers and the Frida session input errors to src/frida

Pure move with git mv and import specifier updates.

* test(architecture): drop the application-providers and application-frida cycles from the layer baseline

* fix(ci): keep provider lanes selecting the ports moved to src/ports

Each lane glob that matched a moved port under src/application gains its src/ports counterpart; the change-scope test pins one moved port per lane.

* refactor(domain): declare the localPath host exception and read HOST_PLATFORM there (#11256)

absoluteLocalPathStringSchema decides which paths are absolute on the running host, so it reads HOST_PLATFORM instead of process.platform. Domain may not import outside domain/contracts; module-layers now declares LAYER_EXCEPTIONS, exact file-to-file imports with a reason, and both the layer count and the pure-layer boundary skip only that import. Any other domain -> platform import still fails.

* refactor(ports): move the doctor check and provider inspection types to src/ports (#11246)

* refactor(ports): move the doctor check and provider inspection types to src/ports

Declaration move from application/Doctor.ts (unchanged text) and import updates; no re-export from Doctor.ts.

* test(architecture): lower the layer baseline after moving the doctor provider types

* refactor(ports): move the packet capture and signal recording ports to src/ports (#11249)

* refactor(ports): move the packet capture and signal recording ports to src/ports

Declaration move (unchanged text) out of the two application services, with import updates.

* test(architecture): lower the layer baseline after moving the capture and signal ports

* refactor(domain): move the analysis error projection schema from contracts to domain (#11251)

* refactor(domain): move the analysis error projection schema from contracts to domain

Declaration move (unchanged text) of the projection schemas that domain modules embed; contracts/errorSchemas.ts keeps the CLI envelope and the published JSON Schema. Import updates only.

* test(architecture): drop the contracts-domain cycle from the layer baseline

* refactor(ports): drop the imports the moved capture, signal and doctor types left behind

Also give the packet capture and signal recording lanes the new port paths, with change-scope cases.

* refactor(resources): add src/resources and move AnalysisCleanupLease and ArtifactReader there (#11259)

* refactor(resources): move AnalysisCleanupLease to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, and the dist paths the verifier scripts load).

* refactor(resources): declare src/resources as a foundation unit

src/resources owns the shared analysis resource modules that process, windows and providers hold; AnalysisCleanupLease is the first. Its tests join the adapters project, the apk signature lane selects it beside src/artifacts, and the layer baseline drops the process and windows imports of the lease.

* test(ci): pin the apk signature lane on the moved cleanup lease

* refactor(resources): move ArtifactReader to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, and the dist path a verifier script loads).

* test(architecture): lower the layer baseline after moving ArtifactReader

windows no longer imports src/artifacts; process -> artifacts 11 -> 9. The CI lanes that selected src/artifacts/ArtifactReader.ts select its new path, pinned in the change-scope test.

* refactor(resources): move ArtifactResourceScope to src/resources (#11265)

* refactor(artifacts): name the output tree and private root capabilities the resource scope releases

ArtifactResourceScope typed its output-tree and private-runtime-root owners with SafeOutputTree (src/artifacts) and PrivateRuntimeRoot (src/process). It only calls rollback() and close(), so it now declares those capabilities itself and names neither unit, which lets it move to src/resources without a resources <-> process cycle. The withheld-export test narrows to SafeOutputTree where it reads the published flag.

* refactor(resources): move ArtifactResourceScope to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, the dist paths verifier scripts load, and the FIFO probe's module-relative URL).

* test(architecture): lower the layer baseline after moving ArtifactResourceScope

process -> artifacts 9 -> 5, and the artifacts <-> dotnet mutual pair is gone. The sqlite and agentenv lanes select the scope at its new path, pinned in the change-scope test.

* refactor(resources): move ArtifactFileOperation to src/resources (#11269)

* refactor(resources): move ArtifactFileOperation to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, and the dist paths verifier scripts load).

* test(architecture): lower the layer baseline after moving ArtifactFileOperation

process -> artifacts 5 -> 1.

* refactor(resources): move readStableArtifact to src/resources (#11271)

* refactor(resources): move readStableArtifact to src/resources

Pure move: git mv plus import specifier rewrites.

* test(architecture): lower the layer baseline after moving readStableArtifact

process no longer imports src/artifacts: process -> artifacts 1 -> 0 and the artifacts <-> process mutual pair is gone. The seven lanes that selected readStableArtifact select its new path, pinned in the change-scope test; the architecture map lists what src/resources owns.

* refactor(hopper): take Linux launcher verification from composition through a port (#11278)

The Hopper launcher imported inspectLinuxHopperLauncher and retryLinuxHopperPublisherCleanup from src/application (the two hopper -> application imports). src/ports/LinuxHopperLauncherVerification.ts now names that capability; src/application/LinuxHopper.ts provides LINUX_HOPPER_LAUNCHER_VERIFICATION, binary composition passes it to HopperProvider, and the provider hands it to the launcher. A launcher built without one refuses a Linux demo launch with reason verification_unavailable before running the launcher. Layer baseline: hopper -> application 2 -> 0.

* refactor(config): move Hopper launcher discovery to a src/hopperPaths foundation unit (#11292)

* refactor(hopper): move the launcher discovery and macOS Hopper paths to src/hopperPaths

Pure move: git mv plus import specifier rewrites.

* refactor(hopper): declare src/hopperPaths as a foundation unit with the Linux launcher candidates

Hopper install paths and launcher discovery are pure path facts that the
Hopper provider, doctor and setup all read. Declare src/hopperPaths in the
foundation layer, add it to the adapters test project, the architecture
map and the package-baseline CI lane, and move the Linux launcher
candidates out of src/application/LinuxHopper.ts into
src/hopperPaths/LinuxHopperPaths.ts so discovery no longer imports
application code.

* refactor(config): leave Hopper launcher discovery to the Hopper provider

parseConfig resolved an unset HOPPER_LAUNCHER_PATH by probing the
filesystem through application-owned discovery, so config imported
application (config -> application 2, application <-> config cycle) and
read process.platform ambiently.

AppConfig.hopperLauncherPath is now the caller's HOPPER_LAUNCHER_PATH
unchanged (string | undefined). src/hopperPaths/HopperLauncherDiscovery.ts
owns the selection (selectedHopperLauncherPath: the configured spelling,
else discovery from the caller environment's home on the provider's
platform); HopperProvider and the two real-Hopper verifiers read it.
Discovery tests move from config.test.ts to src/hopperPaths; a provider
test covers discovery from the provider's own platform and home.

Module layers: config -> application 2 -> 0; application <-> config removed.
Architecture guards: ambient platform reads in parseConfig.ts 2 -> 0.

* refactor(providers): move owned-process prerequisite availability out of application (#11294)

* refactor(providers): move the owned-process prerequisite availability mapping to src/providers

Pure move: git mv plus import specifier rewrites.

* test(architecture): lower the layer baseline after moving owned-process availability

android -> application 1 -> 0; apktool -> application 1 -> 0.

* refactor(process): move the regular-file read owner out of application (#11299)

* refactor(process): move the regular-file read owner from src/application to src/process

Pure move: git mv plus import specifier rewrites.

* test(architecture): lower the layer baseline after moving the regular-file read owner

desktop -> application 5 -> 4; dotnet -> application 2 -> 1.

The agentenv lane listed src/application/RegularFileRead.ts. At its new
path it is a src/process/ shared boundary: fast qualification selects the
code and runtime checks (and the single owning lane, web_source_map, via
src/process/**), and full qualification selects every lane, as for every
other src/process/ module. A second owner entry would only suppress the
web_source_map selection, so the agentenv entry is removed, not renamed.

* refactor(resources): give atomic text writes their own owner (#11302)

* refactor(resources): give atomic text writes their own owner in src/resources

src/application/JsonFiles.ts owned both JSON input reads and the atomic
text write (writeTextFile / writeTextParts and their staged-output
publication). The write side depends only on domain, filesystem and
resource owners, but il2cpp's Ghidra seed writer had to import
application to reach it (il2cpp -> application).

Move the write side verbatim to src/resources/TextFileWrite.ts
(TextWriteCancellation, writeTextFile, writeTextParts and their private
staging, publication and failure classification helpers). JsonFiles keeps
the JSON read owner and reads the shared errno-to-reason classifier
(fileAccessFailureReason) from the write owner instead of a copy.
Importers (il2cpp seed writer, evidence bundle files, desktop build
solves, analysis snapshot files and four boundary tests) read the new
path; no re-export is left in JsonFiles.

* test(architecture): lower the layer baseline after moving the text write owner

il2cpp -> application 1 -> 0.

* refactor(ports): move the desktop build host contract to src/ports (#11303)

* refactor(domain): move the setup cancellation check from src/application to src/domain

Pure move: git mv plus import specifier rewrites.

* refactor(ports): move the desktop build host contract to src/ports

The desktop provider implements doctor's desktop build facts reader and
setup's desktop build host, but the contract it implements lived in
application (DesktopBuildDoctor, SetupDesktopBuild, Doctor's
clientRegistrations signature, ClientRegistrationEnvironment's setting
types), so desktop imported application four times and the two units
were a recorded mutual pair.

src/ports/DesktopBuildHost.ts now holds that contract, moved verbatim:
DesktopBuildCommand, DesktopBuildFacts, DesktopBuildFactsInput,
DesktopBuildSetupFacts, DesktopBuildSetupHost, RecordedProviderSettings
and OwnedProviderSetting. Two names are new: DesktopBuildRegistration,
the registration facts the host reads (client, command and the
recorded-settings names; client registration status satisfies it), and
DesktopBuildRegistrationReader, which replaces
DoctorHost["clientRegistrations"] in the setup host. The facts input's
registration reader returns DesktopBuildRegistration instead of the full
application status; the setup facts' settings are spelled
Readonly<Record<string, string>> (SetupProviderEnvironment's definition).
Application imports the types from the port; no re-export is left.

* test(architecture): lower the layer baseline after the desktop build host port

desktop -> application 4 -> 0; the application <-> desktop mutual pair is gone.

* refactor(domain): define the resolved app bundle resource root beside its schema (#11304)

* refactor(domain): define the resolved app bundle resource root beside its provenance schema

ResolvedAppBundleResourceRoot (an app directory's resource-only identity)
is a pure type over BundleResourceRoot's layout, but it lived in
src/application/AppBundleExecutable.ts, so the native and artifact
providers that receive it imported application.

Move the interface verbatim to src/domain/apple/bundleResourceRoot.ts,
which owns BundleResourceRoot, and point its eight readers there (native
macOS provider and plist source, artifact provider, binary composition,
and the binary session, status, port and bundle-resource session). The
resolver that produces it stays in application.

* test(architecture): lower the layer baseline after moving the resource root type

native -> application 2 -> 0; artifacts -> application 2 -> 1 (the
artifact provider still constructs BundleResourceSession).

* refactor(config): move the pwntools input bound parser to src/config (#11306)

* refactor(config): move the pwntools input bound parser from src/native to src/config

Pure move: git mv plus import specifier rewrites, and the module path in docs/design/rea-limit-inventory.md (table realigned by oxfmt).

* test(architecture): lower the layer baseline after moving the pwntools input bound

config -> native 1 -> 0. The binary_layout and recorded_crash lanes, which
select src/native/pwntools/**, also select src/config/pwntoolsInputLimit*.ts;
ciChangeScope.test.ts pins both.

* refactor(filesystem): move REA cache directory helpers out of config (#11309)

* refactor(filesystem): move the REA cache directory and lexical directory helpers from src/config to src/filesystem

Pure move: git mv plus import specifier rewrites.

* test(architecture): drop the config and filesystem cycle from the layer baseline

config no longer imports filesystem; filesystem still reads the Windows
ChangeTime settle budget from config.

* refactor(windows): break the process and windows import cycle (#11317)

* refactor(domain): move the runtime-control and private-runtime-root refusals from src/process to src/domain

Pure move: git mv plus import specifier rewrites (including the dist path scripts/verify-windows-native.mjs loads).

* refactor(windows): type Job Object cleanup by what a Windows job reports

WindowsOwnedProcess.cleanup() returned process-ownership's
ProcessCleanupResult, so src/windows imported src/process for a type while
process imports windows to supervise Windows trees. A Job Object stop only
ever reports settled-and-signalled or a reason it did not settle; name that
subset WindowsJobCleanupResult in windows. It stays assignable to
ProcessCleanupResult, so the process supervisor reads it unchanged.

* test(architecture): drop the process and windows cycle from the layer baseline

* test(architecture): ratchet cross-provider imports and imports past a provider entry (#11386)

* test(architecture): ratchet cross-provider imports and imports past a provider entry

A provider folder may import the domain, contracts, foundation and ports layers, the shared provider core (src/providers) and its own files; an import of another provider folder is a recorded exception. Application, composition and the CLI/MCP adapters reach a provider only through src/<provider>/index.ts. verify:module-boundaries counts both kinds of import per unit pair in the layer baseline (crossProvider, providerEntry); like the upward counts they may only shrink, and a pair missing from the baseline fails.

* refactor(resources): move StableArtifactFailure and StableArtifactObservation into src/resources (#11387)

* refactor(resources): move StableArtifactFailure and StableArtifactObservation into src/resources

Providers project stable-read failures through StableArtifactFailure next to the other shared provider toolkit owners (ArtifactReader, ArtifactResourceScope, ArtifactFileOperation, AnalysisCleanupLease, readStableArtifact) that already live in src/resources. Under src/artifacts it made every provider that reads a stable artifact import the artifacts provider. Pure move: git mv plus import specifier and baseline updates; the layer baseline drops the provider-boundary counts the move removes.

* refactor(resources): reach the shared provider toolkit through src/resources/index.ts (#11390)

* refactor(resources): import the shared provider toolkit through src/resources/index.ts

Adds src/resources/index.ts, which exports the toolkit names that production code outside src/resources uses, and rewrites those importers (420 files) to import from it, merging each importer's toolkit imports into one declaration. Mechanical: import declarations only.

* test(architecture): reach src/resources only through its entry file

verify:module-boundaries now counts any production import of a src/resources file other than src/resources/index.ts, from any unit, with the imports past a provider entry. The count is renamed from providerEntry to entry ("import past the entry file"); it may only shrink, and src/resources starts at zero.

* test(architecture): cover provider boundary counts through the verifier command

* refactor(resources): move the safe output tree and artifact path owners into src/resources (#11398)

* refactor(resources): move the safe output tree and artifact path owners into src/resources

SafeOutputTree (with its admission, creation failure, readback, cleanup and identity files), StreamBytes, ArtifactPaths and readArtifactFileChunks depend only on domain, filesystem, platform and the toolkit, and browser, firmware, ghidra, javascript, android and apktool use them to publish outputs. Under src/artifacts every such provider imported the artifacts provider. Pure move: git mv, importers moved onto src/resources/index.ts (names added to the entry), the moved files import toolkit modules directly, path keys in the CI scopes and guard baseline follow the move, and the layer baseline drops the removed imports.

* test(architecture): give the shared provider core its own layer below the providers (#11401)

src/providers (deferred client owners and failure attribution) now imports only domain, ports, process, filesystem and the resources toolkit. Declaring it as the providerCore layer, between ports and providers, makes any import from it into a provider folder an upward import that verify:module-boundaries rejects, and lets every unit in the providers layer be a provider folder.

* test(architecture): declare each provider's entry files instead of a provider barrel (#11407)

* chore: ignore the source map parser move (#11348) in blame

* test(architecture): declare inspector's use of the browser CDP client as a provider dependency (#11420)
2026-11-16 03:56:10 +08:00
morluto a93a9f43c9 test(support): copy isolated-repository scripts with their runtime import closure (#11281)
* test(support): copy isolated-repository scripts with their runtime import closure

* fix(test): resolve package imports to the file Node loads in the import closure
2026-11-15 23:49:11 +08:00
morluto 8c052bdec5 test(architecture): ratchet top-level layer direction and mutual imports (#10584)
* test(architecture): ratchet top-level layer direction and mutual imports

Declare a layer for every top-level src/ directory and root source file
(domain, contracts, foundation, providers, application, composition,
adapters) in scripts/lib/module-layers.mjs. verify:module-boundaries now also
builds the production import graph between those units and compares it with
a counted baseline: 45 unit pairs import a higher layer (248 imports) and 23
unit pairs import each other. A new upward pair, more imports on a recorded
pair, a new mutual import, or an undeclared unit fails; shrinkage is
reported so the baseline can be lowered.

* fix(architecture): enforce layers for isolated units
2026-11-15 08:37:04 +08:00
morlutoand吴佳浩 1b36fc2d50 fix(scripts): validate package-map ownership and preserve HTML fallback (#10097)
* fix(website): keep the HTML validator when the Markdown route is absent

A caller that prefers Markdown gets the HTML probe with its conditional headers
deleted, so the Markdown route can be evaluated on its own. When the Markdown
sidecar is missing the worker answers with that probe, which never saw the
caller's `If-None-Match`, so a matching HTML ETag returned 200 instead of 304.

Ask the asset service again with the caller's own request before answering with
HTML. The decision moves into `htmlFallback` so the request handler keeps its
complexity below the repository bound.

Verified by executing `node --test website/worker.test.mjs`: without the change
the new case fails with 200 instead of 304, and all four cases pass with it.
`oxlint` reports no findings and `oxfmt --check` passes. The website worker test
is not part of a CI workflow, so this suite runs locally only.

* fix(scripts): resolve package-map imports in the module-boundary guard

The guard resolved only relative, absolute and `file:` specifiers, so every
`#`-prefixed package-map import returned no target and was skipped. A pure-layer
file importing `#javascript-analysis-worker` passed, while the same import
written relatively failed with a `pure-layer` diagnostic: the gate failed open
on the spelling the package map exists to encourage.

Resolve a package-map specifier to the source file that produces its built
output, then apply the same ownership rules. The package map is read once per
repository root.

Verified with the new `scripts/lib/module-boundaries.test.mjs` (2 pass; the
package-map case failed before the change) and by running the complete guard on
this checkout, which still reports 4138 files with no findings, so the new rule
adds no false positive. `oxfmt --check` passes; `oxlint` reports the same single
pre-existing `failedBoundary` complexity warning it reported before this change.
The script tests are not part of a CI workflow, so this suite runs locally only.

* fix(scripts): normalize package targets as file URLs

---------

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-11-11 08:27:39 -05:00
gensokyo-dev e18594b247 refactor(composition): unify capability bindings and cleanup ownership (#8441)
Bind typed service creation, observed availability and retryable cleanup in one composition owner. Reuse selected CLI/MCP factories and canonical contract groups without copying provider operation inventories.

Closes #8429. Refs #740.

Validated paired real application workflows, actual local Codex CLI Terra/high use, complete Evidence and Unknown checkpoint parity, compiler-backed import boundaries, SDK schemas and final real mixed routing. Automated review findings were fixed at their producing owners. Existing exact-base CodeQL alerts are documented on the PR under the owner-authorized unrelated-check exception; no global alerts or security rules were changed.

Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
2026-11-01 13:30:21 +08:00
morlutoandCursor Agent 249b90c5e3 refactor(javascript): break the semantic analysis import cycle (#8063)
* refactor(javascript): break the semantic analysis import cycle

Split shared semantic facts out of the analysis hub so projectors of
effects, evaluation, and identity no longer import one another in a cycle.

* refactor(javascript): share the import specifier reader

Read static imports in one module used by the boundary checker and both
cycle guards, so those rules cannot drift apart.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-10-30 06:07:49 +08:00
2c3dd946d5 feat(python): inspect CPython pyc headers and marshal code objects (#4826)
* feat(python): inspect CPython pyc headers and marshal code objects

Add inspect_python_pyc / inspect-python-pyc to read one explicit local
CPython 3.7–3.13 .pyc without executing bytecode or recovering source.

* chore(python): drop unused PythonPycHeader export

Knip reported the type as unused after inspect_python_pyc landed.

* fix(python): bound pyc expansion and decode marshal like CPython

- Count a nested code object reached through TYPE_REF once per copy the
  report carries, against max_objects and max_file_bytes, before counting
  or validating the tree
- Charge long digits to max_string_bytes, reject out-of-range and
  unnormalized digits, build the value in one pass, and report integers
  above 256 bits by bit length only
- Decode TYPE_UNICODE with surrogatepass semantics and reject other
  ill-formed UTF-8
- Map only 3.11 magics 3494-3495 to the py311 layout
- Report non-finite float and complex parts as inf, -inf or nan
- Allow an empty co_filename
- Require bytes for co_linetable and co_exceptiontable
- Bind cleanup-failure errors to their retained descriptor leases

* fix(python): list pyc code objects once instead of a recursive tree

Report each distinct code object once in code_objects, top-level first,
with nested_code as indexes. A child shared through TYPE_REF is no longer
copied per reference, and the MCP output schema is no longer recursive.
Names repeated through TYPE_REF still count against max_file_bytes for
each copy the report carries.

* fix(python): bound shared pyc constants and reject malformed tables

- Cache byte-string digests so a buffer shared through TYPE_REF is
  hashed once instead of on every reference.
- Charge every reported co_consts entry, including tables shared
  through TYPE_REF, against max_objects before summaries are built.
- Resolve the inspect-python-pyc path with absoluteCallerPath so
  link/../file.pyc reads the file the filesystem selects.
- Reject TYPE_NULL inside marshal sequences, as CPython does.
- Reject a co_localspluskinds length that does not match
  co_localsplusnames in the parser and the report schema.

* fix(python): bound shared pyc names and read CPython marshal graphs

Charge each reported code-constant name, keep integer bit lengths on the
decoded value, and list code objects nested inside constant containers.
Accept self-referential lists and dicts, marshal version 0 text floats,
empty code names, the original string byte count, and Python set and dict
lengths. Pass the CLI cancellation signal into command cleanup.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(python): bound pyc key expansion and shared nested code

Charge set and dictionary keys before a shared tuple doubles them, list each
nested code object once per owner, and accept code objects as CPython keys.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(python): correct pyc equality, counts, and nested walks

Summarize code objects only after the marshal graph is complete, and
collect nested code with an iterative walk that shares wrapper results
instead of copying every descendant list. Keep tuple boundaries and the
original string bytes in equality keys, and reject negative CPython counts.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(python): bound shared pyc names and keep the first dict key

Charge every copied name-table entry against the object budget before
building the report array, including empty strings that add no bytes.
When dictionary keys compare equal, keep the first key object and
replace only its value, matching CPython.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(python): walk each pyc dictionary child list once

Keep a container's child array on the nested-code frame so a wide
dictionary is not copied on every step of the synchronous marshal walk.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(python): reuse stored pyc dictionary children when combining

The nested walk keeps each container's child list on its frame.
Combining nested code rebuilt that list, and the 8,000-key regression
still accepted the old per-key copy. Use the stored list, and require
that dictionary to finish well under the copy's runtime while still
reporting a nested code object.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(python): keep distinct pyc code objects and reject corrupt ones

Encode each name table's length and entry boundaries in the equality
key so a different name list cannot share a memo key. Walk tuple and
frozenset keys on an explicit stack so a long TYPE_REF chain does not
overflow. Treat code objects CPython rejects for an odd co_code or an
undersized local table as malformed instead of complete coverage.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-10-22 19:00:08 +08:00
gensokyo-dev efab044f30 feat(gpu): inspect static CUDA and HIP code objects (#5813) 2026-10-21 19:06:44 +08:00
gensokyo-dev 98f4072f1f feat(model): inspect GGUF and safetensors declarations (#5603) 2026-10-21 00:50:50 +08:00
JANG BYUNGKUNandgensokyo-dev 833136507d feat(il2cpp): inventory Unity IL2CPP global-metadata images, types and methods (#3807)
* feat(il2cpp): inventory IL2CPP global-metadata images, types and methods

Add inspect_il2cpp_metadata (CLI inspect-il2cpp-metadata), a read-only
in-process decoder for unencrypted Unity global-metadata.dat version 39.
It reports header sections, serialized index widths, images, type
definitions (nesting from the nestedTypes section) and method names.

Unrecognized magic and other versions are unsupported; damaged headers,
overlapping sections, inconsistent record sizes, out-of-range indices and
invalid strings fail with a reason code and no partial success. MCP
detail summary retains the complete Evidence and pages rows through
inspect_analysis_view kind il2cpp-metadata.

Adds an opt-in verify:il2cpp:metadata -- --metadata PATH check.

* feat(il2cpp): deliver metadata summaries by default over MCP

A 112,232-method file produced a 10.5 MB complete response, above the
10 MiB stdio budget. Default MCP delivery is now the retained summary;
detail complete stays available, and the one-shot CLI requests it.

* fix(il2cpp): reject shifted strings, nesting cycles and method owner drift

Review fuzzing showed that moving the strings section offset by one byte
silently renamed every image, type and method. Name indices must now start
a string, which also bounds total decoding by the section size.

Nesting cycles and methods whose declaring type disagrees with the owning
type range are rejected instead of returned. Adds service, shutdown and
index-width coverage, and moves environment-specific measurements out of
the public guide and tool description.

* feat(il2cpp): decode global-metadata versions 29 and 31

Unity 2022.3 writes version 29 or 31 metadata: a 256-byte header of
(offset, size) pairs, fixed 4-byte indices, type records with
elementTypeIndex, and method records that gained returnParameterToken in
version 31. Record counts come from section sizes and must be whole.

Sections report a null count for these versions and index widths report
fixed-width-version. Image, type and method rows keep the same shape, and
the string, nesting and method-ownership checks apply to every version.

* fix(il2cpp): bound report size before serializing and tighten coverage

Rows share decoded names, so a 130 KB file could expand into gigabytes of
JSON before the 64 MiB budget check, ending in an internal RangeError. The
provider now refuses from a lower bound on the serialized rows first.

The decoder also rejects non-empty sections inside the header, methods
outside their declaring type's range and overlapping image type ranges, and
keeps a leading byte order mark in names. Layouts now carry one indexing
mode instead of two coupled flags, and the tool description explains
nested_type_start.

* fix(il2cpp): refuse oversized metadata before decoding rows

Address review findings on the IL2CPP metadata inventory:

- check a lower bound from header row counts before any row object is
  allocated, so a large rejected file no longer builds every row first;
- validate sealed parent Evidence and count its rows once per report
  instead of on every inspect_analysis_view page;
- decode version 39 fixtures with 2- and 4-byte type-definition,
  generic-container and parameter indices.

* docs(il2cpp): attach the decoder comment to readIl2cppMetadata

* fix(il2cpp): deliver complete rows by default like the other inspection tools

inspect_il2cpp_metadata defaulted to detail summary, the only inspection
tool to do so. Omitted detail now returns every row inline, as
inspect_artifact, decode_interface_builder and the capture tools do;
summary stays one argument away and the guide, CLI reference and skill
reference say to select it first for large games, whose complete MCP
delivery is refused at the stdio budget with retained Evidence.

* test(il2cpp): cover narrow-width -1 sentinels and fix the skill's default

An empty image stores its type start as the all-ones value of a one- or
two-byte index; the decoder reads it as -1, but no fixture exercised it,
so removing either conversion passed the suite. The fixture can now append
an empty image, and both widths decode it. The skill still described a
summary default; it now says to select summary first, as the guide does.

* docs(il2cpp): request summary explicitly in the summary example

* chore(il2cpp): hash the verifier metadata through owned file resources

* fix(il2cpp): count escaped name length without building the escaped string

* fix(il2cpp): keep the verifier's check failure and small-table last page

* feat(domain): count JSON string length without building the escaped string

* fix(il2cpp): keep descriptor cleanup owners and share the JSON length count

* test(domain): give the backslash case real backslashes

* fix(il2cpp): select the CLI path and finish the command like the other tools

Follow main's absoluteCallerPath (#4067) and pass the command signal to finishAnalysisCommand.

* fix(il2cpp): select the verifier input path like the CLI

Use absoluteCallerPath (#4067) so a path with a symlink followed by .. names the same file the CLI and MCP inspect.

* feat(il2cpp): add compact composable metadata queries

Retain source-indexed Evidence for filtered batch and field queries. Bound representation growth before serialization, yield decoding for cancellation, and share CLI Evidence publication with desktop inspection. Verify public Unity metadata against independent byte and managed-DLL oracles and exercise actual stdio SDK workflows.

* fix(il2cpp): retain the validated metadata header magic

* test(il2cpp): remove obsolete execution wording exception

* fix(artifacts): preserve export selection and completed source facts

---------

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-10-20 07:20:47 +08:00
0e6eca4085 feat(native): read embedded cargo-auditable Rust dependency lists (#2456)
* feat(native): read embedded cargo-auditable Rust dependency lists

* fix(native): trim PE section padding and compute dependency cycles iteratively

* fix(native): ignore SHT_NOBITS sections and validate dependency edges linearly

* fix(native): bound compiler path scanning and retained hashes

* fix(rust): pass package arrays as named parameterized test cases

* fix(rust): admit graph expansion and preserve resource units

* fix(rust): reject malformed packages, false cycles, and hidden compiler paths

Fail the first malformed cargo-auditable package before Zod collects an
issue per field. Require cyclic dependency indices to match the cycles in
package dependencies. Keep read-only ELF ranges when a section name does
not fit the bounded name window, so a rustc path in that range is still
reported.

* fix(ci): repair integrated checks and Hopper test baseline

* fix(go): verify Mach-O sections against segments

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-10-14 02:50:30 +08:00
YsopwnableandOlorinm 91b8f587cd feat(signals): decode recordings with bounded sigrok output (#2339)
Decode caller-selected protocols from existing recordings through shared
CLI/MCP Evidence. Page literal output lines after complete decoding;
preserve explicit full output, source identity and failed cleanup ownership.

Verified real sigrok-cli 0.7.2 workflows, published UART/SPI/I2C recordings,
independent UART values, selector limits, SDK schemas and cleanup regressions.

Co-authored-by: Olorinm <59321404+Olorinm@users.noreply.github.com>
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
2026-10-12 20:59:02 +00:00
YsopwnableandOlorinm f611d8ce72 feat(captures): inspect recorded packets with bounded TShark delivery (#2318)
Inspect selected fields in existing captures through shared CLI/MCP Evidence.
Page matching frames without changing dissection or two-pass read coverage;
retain failed descriptor/process cleanup ownership and reject excess admission.

Verified with real TShark 4.0.17 and 4.2.2, public Wireshark recordings,
owned HTTP application traffic, real CLI/MCP workflows and schema checks.

Co-authored-by: Olorinm <59321404+Olorinm@users.noreply.github.com>
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
2026-10-12 19:35:35 +00:00
YsopwnableandY0UW1SH aeee5074d1 feat(sqlite): inspect offline snapshots with selective evidence (#2271)
Add offline SQLite database/WAL inspection through the shared CLI/MCP.

Use compact inventory, selected-table schema, exact ordered columns and
bounded row samples while preserving source identity and lossless values.
Retain completed Evidence through late cancellation and private-root cleanup
failures, bound concurrent inspections, and recheck journal validity after
acquisition. Reuse prepared CI runtime artifacts across supported Node lines.

Co-authored-by: Y0UW1SH <29498139+Y0UW1SH@users.noreply.github.com>
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
2026-10-12 18:33:23 +00:00
You Wishandmorluto a1b5d51a8d feat(go): inspect embedded binary build metadata (#1363)
* feat(go): inspect embedded binary build metadata

* fix(go): preserve byte metadata and validate container mappings

* fix(go): support moduleless legacy build metadata

Recognize optional module string headers in declared zero-filled memory while rejecting ambiguous and unmapped pointers. Preserve the original module-pointer field as the zero-byte source anchor.

Classify initial symlink-loop and overlong-path failures as invalid input, with CLI and MCP regressions.

* fix(go): reject undersized PE optional headers

* fix(native): stabilize ELF memory checks and clean up exec wrappers

Use existing parent/group/run-token ownership for caller-selected Python launchers, which can exec through a shell or prlimit. Add cancellation regressions for the valid wrapper and wrong-parent/token cases.

Replace the timing-dependent 30,000-section memory workload with a valid 32 MiB padded ELF under a 64 MiB address-space limit. Check the same image successfully through CLI and MCP before requiring a typed memory failure, preserving the production timeout and all error assertions.

Validation: npm run check and check:fast passed; 61 focused tests passed including Go CLI/MCP and session snapshots. Real decoder probes with pinned packages passed on Python 3.12.3 and 3.12.14. The full local ELF verifier is blocked by this container's procps/process-ownership boundary; the exact pushed head requires GitHub's real-binary-layout lane.

* test: repair Electron fixtures and stabilize catalog startup checks

Declare Electron imports in option, preload override, and path-resolution fixtures after upstream began requiring proven API provenance. Retain all option and preload assertions and adjust exact source ranges for the added import line.

Use the existing bounded acceptance timeout for the cold catalog lifecycle test instead of a separate 15-second ceiling. This retains the coverage allowance and all catalog, error, and cleanup assertions without retries.

Validation: npm run check, final check:fast, formatting and diff checks passed. Source path regression and Go boundary/MCP/service checks passed. All 20 Go CLI cases and both supported-host runtime cases passed on rerun; two macOS-only cases skipped on Linux. A prior contended local run timed out once in a Go CLI diagnostic; that case passed on rerun. Electron process-boundary verification is blocked locally by procps namespace inspection and requires fresh CI.

* test(mcp): isolate nested schema references between tool contracts

Clear Ajv's non-meta schema registry after each root, including compilation failures. Disabling root registration alone leaves nested IDs available to later tools and can let a dangling reference pass the catalog gate.

Add regressions for leakage after successful and failed compilation while retaining shared meta-schema validators. The regression failed before the fix; all 11 schema cases and full npm run check pass. Reviewed independently.

* test(ci): align Go effects and source-map verification contracts

Audit the Go inspector wording as static metadata inspection. Assert retained source declaration indexes in BOM reconstruction and the compiler-derived nested-map oracle. Keep a 45,000-map admission control below the 32 MiB output budget and the 50,000-map overflow case above it with the expanded representation.

Validation: reproduced all four failing assertions, then passed 120 focused tests and the final admission suite. npm run check and real Chrome 154 / esbuild 0.25.10 source-map verification passed, including all four nested-map scenarios and verified process lineage.

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 11:34:02 +08:00
Thang Luuandmorluto ffaf2c12f1 feat(wasm): inspect local artifacts with WABT (#1533)
* feat(wasm): inspect local artifacts with WABT

* fix(wasm): preserve custom names and failed cleanup ownership

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-11 19:49:00 +08:00
morluto abc4f47683 build: separate runtime artifacts and supervise command ownership 2026-10-09 20:11:17 +08:00
Ysopwnable 7af7bc88ce feat(evm): inspect offline bytecode interfaces through EVMole (#1051)
* feat(evm): inspect offline bytecode interfaces through evmole

* fix(evm): distinguish unsupported bytecode targets

* style(evm): format verifier string-prefix checks
2026-10-08 15:32:05 +08:00
Ysopwnable 6e4535c101 refactor(artifacts): move inventory and extraction into provider owners (#1032) 2026-10-08 05:51:14 +08:00
Ysopwnable 6aa9afb549 refactor(process): separate capture implementation from analyst workflows (#988)
* refactor(process): separate capture implementation from analyst workflows

* fix(ci): generate source catalog before shard tests
2026-10-08 00:46:21 +08:00
Ysopwnable 33d4761cc7 refactor(binary): move production composition outside application workflows (#965) 2026-10-07 21:56:58 +08:00
ysopwnable ef1a0cc65a refactor(apple): group artifact producers and verification (#952)
* refactor(apple): group artifact producers and verification

* test(apple): run affected native plist CLI regressions
2026-10-07 21:09:33 +08:00
ysopwnable f0a68dce60 refactor(artifacts): isolate JavaScript file acquisition (#916) 2026-10-07 17:57:33 +08:00
ysopwnable b808e2d6bb refactor(provider): declare deep capabilities from source (#892) 2026-10-07 15:41:50 +08:00
ysopwnable 021ba690b0 refactor: give Inspector its own capability directory (#869) 2026-10-07 13:53:25 +08:00
N0zoM1z0 3427593daf build: verify resolved module boundaries (#862) 2026-10-07 13:02:28 +08:00