refactor(domain): bound a first batch of constant-maximum slices with boundedList (#11296)

* refactor(domain): bound a first batch of constant-maximum slices with boundedList

* fix(domain): describe a bounded list with nothing retained without a leading separator

* refactor(domain): bound eleven counted list samples through boundedList (#11421)

Desktop state differences, guidance subsection pointers, native output contract issues, APK v1 duplicate-name samples, environment write refusals, desktop build action logs and credential-named saved-value pointers already reported a count or a cut beside a sliced list; the slice and the count now come from one boundedList. constant-maximum-slice: 54 -> 43.
This commit is contained in:
morluto authored and GitHub committed 2026-11-16 04:24:58 +08:00
1 parent 66ec6a7261
commit 673050f7bc
18 files changed
+130 -86

No files matched your search

@@ -1,18 +1,8 @@
{
"src/adb/AdbCommand.ts": 1,
"src/apktool/ApktoolProvider.ts": 1,
"src/application/EnhancedTools.ts": 1,
"src/application/GuidanceAccess.ts": 1,
"src/application/desktop/DesktopBuildActionLog.ts": 1,
"src/application/environment/environmentBuildReport.ts": 1,
"src/application/environment/environmentCompare.ts": 1,
"src/application/environment/environmentReplay.ts": 1,
"src/application/javascript/JavaScriptArtifactAnalysis.ts": 1,
"src/application/releaseExposure/ReleaseExposureService.ts": 1,
"src/desktop/DesktopSessionObservations.ts": 1,
"src/domain/analysisView/environmentStateWriteApply.ts": 1,
"src/domain/apkSignature/apkV1Signature.ts": 1,
"src/domain/desktop/appExportUnowned.ts": 1,
"src/domain/desktop/appTaskDraft.ts": 4,
"src/domain/desktop/appTaskDraftAdded.ts": 3,
"src/domain/desktop/appTaskDraftAlternatives.ts": 1,
@@ -27,12 +17,7 @@
"src/domain/desktop/appTaskDraftNotes.ts": 1,
"src/domain/desktop/appTaskDraftText.ts": 1,
"src/domain/desktop/appTaskDraftValues.ts": 1,
"src/domain/desktop/desktopCapture.ts": 1,
"src/domain/desktop/memberPairing.ts": 1,
"src/domain/desktop/selectorCandidates.ts": 1,
"src/domain/desktop/stateChanges.ts": 5,
"src/domain/firmware/dfuse.ts": 1,
"src/domain/firmware/uf2.ts": 1,
"src/domain/native/nativeProviderOutput.ts": 1,
"src/domain/releaseExposure.ts": 2
}
+4 -4
View File
@@ -1,3 +1,4 @@
import { boundedList } from "../domain/boundedList.js";
import { permitsCapabilityFallback } from "./CapabilityFallback.js";
import { withOverviewInventoryCoverage } from "../domain/native/inventoryCoverage.js";
import type { NativeCallGraph } from "../domain/native/nativeCallGraph.js";
@@ -328,14 +329,13 @@ export class EnhancedTools {
);
const addresses = [...new Set(candidates.map(({ address }) => address))];
const scannedAddresses = addresses.slice(0, MAX_DISPATCH_METADATA_RECORDS);
const scanned = boundedList(addresses, MAX_DISPATCH_METADATA_RECORDS);
const bindingsExecution = await this.#observe(
"inspect_native_dispatch_metadata",
{
max_records: MAX_DISPATCH_METADATA_RECORDS,
objc_class_import_addresses: scannedAddresses,
objc_class_import_addresses_complete:
addresses.length <= MAX_DISPATCH_METADATA_RECORDS,
objc_class_import_addresses: [...scanned.items],
objc_class_import_addresses_complete: scanned.omitted === 0,
},
signal,
);
+4 -6
View File
@@ -1,3 +1,4 @@
import { boundedList, type BoundedList } from "../domain/boundedList.js";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import type { z } from "zod";
@@ -505,7 +506,7 @@ const isWithin = (section: GuideSection, ancestor: GuideSection): boolean => {
const subsectionPointers = (
match: RankedSection,
coverage: readonly TermCoverage[],
): { readonly pointers: readonly TermCoverage[]; readonly omitted: number } => {
): BoundedList<TermCoverage> => {
const descendants: TermCoverage[] = [];
// Document order keeps every subsection contiguous after its parent.
for (let index = match.index + 1; index < coverage.length; index += 1) {
@@ -530,10 +531,7 @@ const subsectionPointers = (
for (const word of best.own) remaining.delete(word);
pointers.push(best);
}
return {
pointers: pointers.slice(0, MAX_SUBSECTION_POINTERS),
omitted: Math.max(0, pointers.length - MAX_SUBSECTION_POINTERS),
};
return boundedList(pointers, MAX_SUBSECTION_POINTERS);
};
const presentMatch = (
@@ -556,7 +554,7 @@ const presentMatch = (
relevance: `Matched ${matched.join(", ")} in this section's own text.`,
context: contextFor(section.ownContent, matched),
};
const { pointers, omitted } = subsectionPointers(match, coverage);
const { items: pointers, omitted } = subsectionPointers(match, coverage);
return {
...common,
relevance: `Matched ${matched.join(", ")} only across different subsections; no single subsection contains every term.`,
@@ -1,3 +1,4 @@
import { boundedList } from "../../domain/boundedList.js";
import type { ComputerAction } from "../../domain/desktop/computerActions.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { utf8HeadExcerpt } from "../../domain/utf8HeadExcerpt.js";
@@ -42,12 +43,11 @@ const bounded = (
return { value: text, cut: truncated };
}
if (Array.isArray(value)) {
const items = value
.slice(0, LOGGED_LIST_ITEMS)
.map((item) => bounded(item, redact));
const kept = boundedList(value, LOGGED_LIST_ITEMS);
const items = kept.items.map((item) => bounded(item, redact));
return {
value: items.map((item) => item.value),
cut: value.length > items.length || items.some((item) => item.cut),
cut: kept.omitted > 0 || items.some((item) => item.cut),
};
}
if (value === null || typeof value !== "object") return { value, cut: false };
@@ -1,3 +1,4 @@
import { boundedList } from "../../domain/boundedList.js";
import { escapeJsonPointerToken } from "../../domain/jsonPointer.js";
import { z } from "zod";
import { basename } from "node:path";
@@ -371,13 +372,14 @@ export const savedCredentialWarnings = (
unmarked(action.save, "save");
unmarked(action.save_response?.save, "save_response/save");
});
const reported = boundedList(pointers, REPORTED_POINTERS);
return pointers.length === 0
? []
: [
{
code: "credential-named-saved-values",
message: `${String(pointers.length)} saved values have credential-like names but are not marked secret, so the capture records them unredacted; mark them \`secret: true\` and record again before sharing.`,
pointers: pointers.slice(0, REPORTED_POINTERS),
pointers: [...reported.items],
},
];
};
@@ -1,3 +1,4 @@
import { boundedList } from "../../domain/boundedList.js";
import {
ownMember,
decodedSegment,
@@ -291,8 +292,10 @@ const stepOf = (
outcome: { env_status: number | null; differences: Difference[] },
): CompareStep => {
const categories = [...new Set(outcome.differences.map((d) => d.category))];
const differences = outcome.differences.slice(0, STEP_DIFFERENCE_LIMIT);
const omitted = outcome.differences.length - differences.length;
const { items: differences, omitted } = boundedList(
outcome.differences,
STEP_DIFFERENCE_LIMIT,
);
return {
...base,
tool: call?.tool.name ?? null,
@@ -302,7 +305,7 @@ const stepOf = (
(difference) => difference.category === "order",
),
categories,
differences,
differences: [...differences],
differences_total: outcome.differences.length,
differences_omitted: omitted,
differences_truncated: omitted > 0,
@@ -1,3 +1,4 @@
import { boundedList } from "../../domain/boundedList.js";
import { createHash } from "node:crypto";
import { posix } from "node:path";
@@ -725,10 +726,13 @@ export const htmlInlineScriptLimitation = ({
script_count: count,
scripts,
}: JavaScriptHtmlInlineScriptsObservation): string => {
const lines = scripts
.slice(0, HTML_INLINE_SCRIPT_LIMITATION_LINES)
.map(({ location }) => String(location.start.line));
const unnamed = count - lines.length;
const listed = boundedList(
scripts.map(({ location }) => String(location.start.line)),
HTML_INLINE_SCRIPT_LIMITATION_LINES,
count - scripts.length,
);
const lines = listed.items;
const unnamed = listed.omitted;
const one = count === 1;
return `${path} has ${String(count)} inline JavaScript ${one ? "body" : "bodies"} starting at line${one ? "" : "s"} ${lines.join(", ")}${unnamed > 0 ? ` and ${String(unnamed)} more` : ""} that ${one ? "was" : "were"} not analyzed; endpoints, storage, imports and other facts in ${one ? "it" : "them"} are absent from the evidence.`;
};
@@ -1,3 +1,4 @@
import { boundedList } from "../../domain/boundedList.js";
import { basename, dirname, posix, win32 } from "node:path";
import { ArtifactReaderFailure } from "../../resources/index.js";
@@ -845,11 +846,13 @@ const limitNativeSample = (
(ranked.get(left.path) ?? 0) - (ranked.get(right.path) ?? 0),
);
const preferredPaths = new Set(preferred.map((image) => image.path));
const kept = [
...preferred,
...scan.native_images.filter((image) => !preferredPaths.has(image.path)),
].slice(0, MAX_RELEASE_EXPOSURE_NATIVE_IMAGES);
const omittedNative = scan.native_images.length - kept.length;
const { items: kept, omitted: omittedNative } = boundedList(
[
...preferred,
...scan.native_images.filter((image) => !preferredPaths.has(image.path)),
],
MAX_RELEASE_EXPOSURE_NATIVE_IMAGES,
);
const keptPaths = new Set(kept.map((image) => image.path));
// With no named host, any sampled sibling could be it, so none settles alone.
const hostsAmong = (
@@ -1,3 +1,4 @@
import { boundedList } from "../boundedList.js";
import { ellipsisExcerpt } from "../excerpt.js";
import { jsonPointerTokens } from "../jsonPointer.js";
import type { JsonValue } from "../jsonValue.js";
@@ -101,11 +102,11 @@ const LISTED_NAME_CHARS = 120;
/** Captured member names quoted, so a separator in one cannot read as another, and bounded in count and length. */
const listed = (members: readonly string[]): string => {
if (members.length === 0) return "none";
const shown = members
.slice(0, LISTED_MEMBERS)
const { items, omitted } = boundedList(members, LISTED_MEMBERS);
const shown = items
.map((member) => JSON.stringify(ellipsisExcerpt(member, LISTED_NAME_CHARS)))
.join(", ");
return members.length > LISTED_MEMBERS
return omitted > 0
? `${shown}, … (${String(members.length)} members; all in the state Evidence)`
: shown;
};
+4 -2
View File
@@ -16,6 +16,7 @@
* state per record (up to ~11M records in a 512 MiB Zip64 file) and only a few
* names decoded.
*/
import { boundedList } from "../boundedList.js";
import { type Result, err, ok } from "../result.js";
import {
canonicalNameHash,
@@ -226,9 +227,10 @@ const duplicateNames = (
}
const sampled = (firsts: number[]): ApkDuplicateNameSample => {
firsts.sort((a, b) => a - b);
const { items, omitted } = boundedList(firsts, MAX_DUPLICATE_NAME_SAMPLE);
return {
count: firsts.length,
sample: firsts.slice(0, MAX_DUPLICATE_NAME_SAMPLE).map((i) => {
count: items.length + omitted,
sample: items.map((i) => {
const start = starts[i] ?? 0;
const storedBytes = lengths[i] ?? 0;
return {
+16 -1
View File
@@ -1,6 +1,10 @@
import { expect, it } from "vitest";
import { BoundedListCollector, boundedList } from "./boundedList.js";
import {
BoundedListCollector,
boundedList,
describeBoundedList,
} from "./boundedList.js";
it("retains up to the maximum and counts every item past it", () => {
expect(boundedList([1, 2], 3)).toEqual({ items: [1, 2], omitted: 0 });
@@ -22,3 +26,14 @@ it("collects up to the maximum and counts later pushes", () => {
expect(collector.retains("c")).toBe(false);
expect(collector.toList()).toEqual({ items: ["a", "b"], omitted: 2 });
});
it("names the retained items and counts the rest", () => {
expect(describeBoundedList(boundedList(["a", "b"], 3), "; ")).toBe("a; b");
expect(describeBoundedList(boundedList(["a", "b", "c", "d"], 2), ", ")).toBe(
"a, b, and 2 more",
);
// Nothing retained: no leading separator.
expect(describeBoundedList(boundedList(["a", "b"], 0), ", ")).toBe(
"and 2 more",
);
});
+15
View File
@@ -42,3 +42,18 @@ export class BoundedListCollector<T> {
return { items: [...this.#items], omitted: this.#omitted };
}
}
/**
* The retained items joined by `separator`, then "and N more" for the omitted
* ones: `a; b; and 3 more`.
*/
export const describeBoundedList = (
list: BoundedList<string>,
separator: string,
): string => {
if (list.omitted === 0) return list.items.join(separator);
const rest = `and ${String(list.omitted)} more`;
return list.items.length === 0
? rest
: `${list.items.join(separator)}${separator}${rest}`;
};
+3 -5
View File
@@ -1,3 +1,4 @@
import { boundedList, describeBoundedList } from "../boundedList.js";
import {
STATE_PATH_INPUTS,
STATE_PATH_INPUTS_MARKDOWN,
@@ -163,11 +164,8 @@ export const runtimeSeeds = (
};
/** Names as a list, the first eight named and the rest counted. */
export const counted = (names: readonly string[]): string => {
const named = names.slice(0, MAX_LISTED).join(", ");
const rest = names.length - MAX_LISTED;
return rest > 0 ? `${named}, and ${String(rest)} more` : named;
};
export const counted = (names: readonly string[]): string =>
describeBoundedList(boundedList(names, MAX_LISTED), ", ");
/** Home paths as a list, the first eight named and the rest counted. */
const listed = (paths: readonly string[], markdown: boolean): string =>
+4 -2
View File
@@ -1,3 +1,4 @@
import { boundedList } from "../boundedList.js";
import { z } from "zod";
import { runtimeFile } from "./runtimeFiles.js";
@@ -145,6 +146,7 @@ export const checkpointTaken = (
(left.path < right.path ? -1 : left.path > right.path ? 1 : 0),
)
.map(({ path }) => relative(path));
const changedFiles = boundedList(files, MAX_ACKNOWLEDGED_FILES);
return {
kind: "checkpoint",
name: checkpoint.name,
@@ -157,8 +159,8 @@ export const checkpointTaken = (
(sum, file) => sum + file.size,
0,
),
changed_files: files.slice(0, MAX_ACKNOWLEDGED_FILES),
more_changed_files: Math.max(0, files.length - MAX_ACKNOWLEDGED_FILES),
changed_files: [...changedFiles.items],
more_changed_files: changedFiles.omitted,
};
};
+24 -12
View File
@@ -5,6 +5,7 @@ import { holdsTagOnly, pairMembers } from "./memberPairing.js";
import { memberLookup } from "./viewPointer.js";
import { zipEntryAt, zipLeavesOut } from "./zipView.js";
import { isRecord } from "../isRecord.js";
import { boundedList, type BoundedList } from "../boundedList.js";
const MAX_LISTED = 100;
@@ -208,6 +209,27 @@ const compareTrees = (
};
};
/** Each list bounded to `MAX_LISTED`, with how many it held in all. */
const listed = (
added: readonly string[],
removed: readonly string[],
changed: readonly string[],
) => {
const total = ({ items, omitted }: BoundedList<string>) =>
items.length + omitted;
const a = boundedList(added, MAX_LISTED);
const r = boundedList(removed, MAX_LISTED);
const c = boundedList(changed, MAX_LISTED);
return {
added: a.items,
removed: r.items,
changed: c.items,
added_count: total(a),
removed_count: total(r),
changed_count: total(c),
};
};
const compareMaps = (
kind: DesktopStateDifference["kind"],
before: ReadonlyMap<string, string>,
@@ -224,12 +246,7 @@ const compareMaps = (
for (const key of before.keys()) if (!after.has(key)) removed.push(key);
return {
kind,
added: added.slice(0, MAX_LISTED),
removed: removed.slice(0, MAX_LISTED),
changed: changed.slice(0, MAX_LISTED),
added_count: added.length,
removed_count: removed.length,
changed_count: changed.length,
...listed(added, removed, changed),
complete: true,
};
};
@@ -256,12 +273,7 @@ const lineDifference = (
}
return {
kind: "lines",
added: added.slice(0, MAX_LISTED),
removed: removed.slice(0, MAX_LISTED),
changed: [],
added_count: added.length,
removed_count: removed.length,
changed_count: 0,
...listed(added, removed, []),
complete: true,
};
};
+5 -1
View File
@@ -1,3 +1,4 @@
import { boundedList, describeBoundedList } from "../boundedList.js";
import { crc32 } from "node:zlib";
import type { DfuSeMetadata } from "../artifactFormatMetadata.js";
@@ -117,7 +118,10 @@ const formatFailure = (
/** At most NAMED_ELEMENTS descriptions, then a count of the rest of `total`. */
const named = (items: readonly string[], total = items.length): string =>
`${items.slice(0, NAMED_ELEMENTS).join("; ")}${total > NAMED_ELEMENTS ? `; and ${String(total - NAMED_ELEMENTS)} more` : ""}`;
describeBoundedList(
boundedList(items, NAMED_ELEMENTS, total - items.length),
"; ",
);
class RetainingDfuSeDecoder implements RegionDecoder<DfuSeImage> {
readonly #bytes: Uint8Array;
+2 -1
View File
@@ -1,3 +1,4 @@
import { boundedList, describeBoundedList } from "../boundedList.js";
import type { Uf2Metadata } from "../artifactFormatMetadata.js";
import { err, ok, type Result } from "../result.js";
import { mergeArenaRuns, type RunConflict } from "./addressRuns.js";
@@ -105,7 +106,7 @@ const familyText = (familyId: number | null): string => {
/** At most NAMED_GROUPS descriptions, then a count of the rest. */
const named = (items: readonly string[]): string =>
`${items.slice(0, NAMED_GROUPS).join("; ")}${items.length > NAMED_GROUPS ? `; and ${String(items.length - NAMED_GROUPS)} more` : ""}`;
describeBoundedList(boundedList(items, NAMED_GROUPS), "; ");
/** Recognize a file only by a complete first block with all three magic numbers. */
export const hasUf2Block = (prefix: Uint8Array): boolean =>
+16 -17
View File
@@ -1,3 +1,4 @@
import { boundedList } from "../boundedList.js";
import { z } from "zod";
import { err, type Result } from "../result.js";
import { AnalysisOutputError } from "../analysisErrorCore.js";
@@ -60,24 +61,22 @@ export const outputContractDiagnostics = (
cause: z.ZodError,
value?: unknown,
): Readonly<Record<string, JsonValue>> => {
const located = locatedIssues(cause.issues);
const located = boundedList(locatedIssues(cause.issues), MAX_CONTRACT_ISSUES);
return {
contract_issue_count: located.length,
contract_issues: located
.slice(0, MAX_CONTRACT_ISSUES)
.map(({ issue, path, branches }) => ({
path: path.map((key) => (typeof key === "number" ? key : String(key))),
code: issue.code,
...(branches.length === 0 ? {} : { union_branches: [...branches] }),
...(issue.code === "invalid_type"
? {
expected: issue.expected,
...(value === undefined
? {}
: { received: jsonKind(valueAt(value, path)) }),
}
: {}),
})),
contract_issue_count: located.items.length + located.omitted,
contract_issues: located.items.map(({ issue, path, branches }) => ({
path: path.map((key) => (typeof key === "number" ? key : String(key))),
code: issue.code,
...(branches.length === 0 ? {} : { union_branches: [...branches] }),
...(issue.code === "invalid_type"
? {
expected: issue.expected,
...(value === undefined
? {}
: { received: jsonKind(valueAt(value, path)) }),
}
: {}),
})),
};
};