From 2f5f02f444ca0449427914538811c13ec0be291b Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Tue, 24 Nov 2026 16:55:02 +0800 Subject: [PATCH] refactor(application): consolidate configuration and observation helpers (#14322) * refactor(application): consolidate configuration and observation helpers * refactor(config): leave optional launch parsers to their existing change --- src/application/GooseConfigurationYaml.ts | 30 +---- src/application/HermesConfigurationYaml.ts | 35 +----- src/application/MacHopper.ts | 10 +- ...constructionObligationLedgerDiagnostics.ts | 25 ---- ...econstructionObligationLedgerEvaluation.ts | 23 +++- src/application/YamlConfigurationSource.ts | 27 +++++ .../JavaScriptApplicationWorkflowEvidence.ts | 111 +++++++----------- src/browser/CdpObservationSession.ts | 40 ++----- 8 files changed, 109 insertions(+), 192 deletions(-) diff --git a/src/application/GooseConfigurationYaml.ts b/src/application/GooseConfigurationYaml.ts index 2fbfc821645..e7e5dff8ced 100644 --- a/src/application/GooseConfigurationYaml.ts +++ b/src/application/GooseConfigurationYaml.ts @@ -18,6 +18,8 @@ import { import { materializeUnresolvedYamlAliases, retainYamlConfigurationSource, + initializeEmptyYamlMapping, + yamlConfigurationValue, yamlAliasValues, retainYamlScalarSource, } from "./YamlConfigurationSource.js"; @@ -162,14 +164,6 @@ class GooseDuplicateMemberError extends GooseConfigurationYamlError { } } -const emptyRoot = (root: Document["contents"]): boolean => - root === null || - (isScalar(root) && - root.value === null && - root.source === "" && - root.tag === undefined && - root.anchor === undefined); - /** Recover a diagnostic key path from the parser-owned duplicate position. */ const duplicatePath = ( node: unknown, @@ -209,16 +203,8 @@ const parseGooseDocument = (text: string): Document => { }; const gooseDocumentValue = (document: Document): unknown => { - if (emptyRoot(document.contents)) return {}; try { - return document.toJS({ - reviver: (_key, value) => - typeof value === "bigint" && - value >= BigInt(Number.MIN_SAFE_INTEGER) && - value <= BigInt(Number.MAX_SAFE_INTEGER) - ? Number(value) - : value, - }); + return yamlConfigurationValue(document); } catch (cause: unknown) { throw new GooseConfigurationYamlError( "Goose YAML values could not be resolved", @@ -248,15 +234,7 @@ export const editGooseConfigurationYaml = ( // Resolve against the original graph before editing, including the YAML // library's native alias-expansion admission. gooseDocumentValue(document); - const root = document.contents; - if (emptyRoot(root)) { - const map = document.createNode({}); - if (isScalar(root)) - map.commentBefore = [root.commentBefore, root.comment] - .filter((comment) => comment !== undefined) - .join("\n"); - document.contents = map; - } + initializeEmptyYamlMapping(document); if (!isMap(document.contents)) throw new GooseConfigurationYamlError( "Goose configuration root must be a mapping", diff --git a/src/application/HermesConfigurationYaml.ts b/src/application/HermesConfigurationYaml.ts index 670235882f8..dc35da265d8 100644 --- a/src/application/HermesConfigurationYaml.ts +++ b/src/application/HermesConfigurationYaml.ts @@ -22,6 +22,8 @@ import { import { materializeUnresolvedYamlAliases, retainYamlConfigurationSource, + initializeEmptyYamlMapping, + yamlConfigurationValue, yamlAliasValues, retainYamlScalarSource, yamlNumericValuesEqual, @@ -259,16 +261,6 @@ export const stringifyHermesConfigurationYaml = ( ): string => new Document(document, createHermesYamlOptions()).toString({ lineWidth: 0 }); -// A comment-only document has no root; a bare marker has an unwritten null -// scalar. Explicit null values, tags and anchors remain actual values. -const isEmptyYamlRoot = (root: Document["contents"]): boolean => - root === null || - (isScalar(root) && - root.value === null && - root.source === "" && - root.tag === undefined && - root.anchor === undefined); - const parseHermesDocument = (text: string) => { const document = parseDocument(text, createHermesYamlOptions()); const error = document.errors[0]; @@ -382,17 +374,8 @@ const inheritedYamlMapOverride = ( }; /** Parse a Hermes `config.yaml`, preserving the distinction between no root and explicit null. */ -export const parseHermesConfigurationYaml = (text: string): unknown => { - const document = parseHermesDocument(text); - return isEmptyYamlRoot(document.contents) - ? {} - : document.toJS({ - reviver: (_key, value) => - typeof value === "bigint" && Number.isSafeInteger(Number(value)) - ? Number(value) - : value, - }); -}; +export const parseHermesConfigurationYaml = (text: string): unknown => + yamlConfigurationValue(parseHermesDocument(text)); /** Set or delete one value in a Hermes `config.yaml`, keeping the rest as written. */ export const editHermesConfigurationYaml = ( @@ -402,15 +385,7 @@ export const editHermesConfigurationYaml = ( ): string => { // A plain Document, so a bare `---` root can be replaced by a new map. const document: Document = parseHermesDocument(text); - const root = document.contents; - if (isEmptyYamlRoot(root)) { - const map = document.createNode({}); - if (isScalar(root)) - map.commentBefore = [root.commentBefore, root.comment] - .filter((comment) => comment !== undefined) - .join("\n"); - document.contents = map; - } + initializeEmptyYamlMapping(document); for (let length = 1; length < path.length; length++) { const parent = resolveYamlEditPath(document, path.slice(0, length)); const previous = document.getIn(parent, true); diff --git a/src/application/MacHopper.ts b/src/application/MacHopper.ts index ca2e968ca40..544fbba0298 100644 --- a/src/application/MacHopper.ts +++ b/src/application/MacHopper.ts @@ -541,15 +541,7 @@ export const systemMacHopperInstallHost = ( ); return declared.data.LSMinimumSystemVersion; }, - async destinationExists(path) { - try { - await access(path); - return true; - } catch (cause: unknown) { - if (isMissingPath(cause)) return false; - throw cause; - } - }, + destinationExists: pathExists, installBundle: (source, destination, replaceExisting) => installMacHopperBundle( source, diff --git a/src/application/ReconstructionObligationLedgerDiagnostics.ts b/src/application/ReconstructionObligationLedgerDiagnostics.ts index 25a2f523f68..1c0c0bc2807 100644 --- a/src/application/ReconstructionObligationLedgerDiagnostics.ts +++ b/src/application/ReconstructionObligationLedgerDiagnostics.ts @@ -6,33 +6,8 @@ import type { Evidence } from "../domain/evidence.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; type Diagnostic = ReconstructionObligation["diagnostics"][number]; -type Binding = NonNullable; type Contradiction = ReconstructionObligationManifest["contradictions"][number]; -export const groupManifestBindings = ( - manifest: ReconstructionObligationManifest, -): ReadonlyMap => { - const grouped = new Map(); - for (const binding of manifest.bindings) - grouped.set(binding.obligation_id, [ - ...(grouped.get(binding.obligation_id) ?? []), - binding, - ]); - return grouped; -}; - -export const groupManifestContradictions = ( - manifest: ReconstructionObligationManifest, -): ReadonlyMap => { - const grouped = new Map(); - for (const contradiction of manifest.contradictions) - grouped.set(contradiction.obligation_id, [ - ...(grouped.get(contradiction.obligation_id) ?? []), - contradiction, - ]); - return grouped; -}; - export const addObligationDiagnostic = ( diagnostics: Diagnostic[], code: Diagnostic["code"], diff --git a/src/application/ReconstructionObligationLedgerEvaluation.ts b/src/application/ReconstructionObligationLedgerEvaluation.ts index 0d1915e6587..82134d5943b 100644 --- a/src/application/ReconstructionObligationLedgerEvaluation.ts +++ b/src/application/ReconstructionObligationLedgerEvaluation.ts @@ -27,8 +27,6 @@ import { import { addObligationDiagnostic as addDiagnostic, contradictionDiagnostics, - groupManifestBindings, - groupManifestContradictions, uniqueObligationDiagnostics as uniqueDiagnostics, } from "./ReconstructionObligationLedgerDiagnostics.js"; import { @@ -41,6 +39,18 @@ import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; type Diagnostic = ReconstructionObligation["diagnostics"][number]; type Binding = NonNullable; +const groupByObligation = ( + entries: readonly T[], +): ReadonlyMap => { + const groups = new Map(); + for (const entry of entries) { + const group = groups.get(entry.obligation_id); + if (group === undefined) groups.set(entry.obligation_id, [entry]); + else group.push(entry); + } + return groups; +}; + interface EvaluationContext { readonly candidates: ReadonlyMap; readonly evidence: ReadonlyMap; @@ -49,7 +59,10 @@ interface EvaluationContext { ReturnType >; readonly bindings: ReadonlyMap; - readonly contradictions: ReturnType; + readonly contradictions: ReadonlyMap< + string, + Readonly + >; } export const evaluateReconstructionObligationLedger = ({ @@ -130,8 +143,8 @@ const createEvaluationContext = ( parseReconstructionProofEvidence(record), ]), ), - bindings: groupManifestBindings(manifest), - contradictions: groupManifestContradictions(manifest), + bindings: groupByObligation(manifest.bindings), + contradictions: groupByObligation(manifest.contradictions), }); const findOrphanManifestIds = ( diff --git a/src/application/YamlConfigurationSource.ts b/src/application/YamlConfigurationSource.ts index 0483279680e..9baedb8594a 100644 --- a/src/application/YamlConfigurationSource.ts +++ b/src/application/YamlConfigurationSource.ts @@ -40,6 +40,33 @@ const normalizeYamlInteger = (_key: unknown, value: unknown): unknown => ? Number(value) : value; +// A comment-only document has no root; a bare marker has an unwritten null +// scalar. Explicit null values, tags and anchors remain actual values. +const isEmptyYamlRoot = (root: Document["contents"]): boolean => + root === null || + (isScalar(root) && + root.value === null && + root.source === "" && + root.tag === undefined && + root.anchor === undefined); + +export const yamlConfigurationValue = (document: Document): unknown => + isEmptyYamlRoot(document.contents) + ? {} + : document.toJS({ reviver: normalizeYamlInteger }); + +export const initializeEmptyYamlMapping = (document: Document): void => { + const root = document.contents; + if (isEmptyYamlRoot(root)) { + const map = document.createNode({}); + if (isScalar(root)) + map.commentBefore = [root.commentBefore, root.comment] + .filter((comment) => comment !== undefined) + .join("\n"); + document.contents = map; + } +}; + const containsRetainedSource = ( roots: readonly unknown[], retainedSources: ReadonlySet, diff --git a/src/application/javascript/JavaScriptApplicationWorkflowEvidence.ts b/src/application/javascript/JavaScriptApplicationWorkflowEvidence.ts index c3ecf1743c6..ea28c974f84 100644 --- a/src/application/javascript/JavaScriptApplicationWorkflowEvidence.ts +++ b/src/application/javascript/JavaScriptApplicationWorkflowEvidence.ts @@ -12,18 +12,22 @@ import type { JavaScriptSemanticTraceResult } from "../../domain/javascript/java import type { SourceToBundleComparisonResult } from "../../domain/javascript/sourceToBundleComparisonSchemas.js"; import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "../../domain/investigationProviders.js"; -/** Create derived Evidence for one bounded application-graph feature trace. */ -export const createApplicationFeatureTraceEvidence = ( - subject: EvidenceSubjectTarget | undefined, +const workflowEvidence = ( + predicateType: string, + operation: string, parameters: EvidenceObservation["parameters"], - result: ApplicationFeatureTraceResult, + result: { + readonly limitations: readonly string[]; + readonly evidence_links: readonly string[]; + }, + subject?: EvidenceSubjectTarget, ): Evidence => createEvidence( subject ?? unknownTarget("derived-from-linked-evidence"), JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, { - predicateType: "rea.application-feature-trace", - operation: "trace_application_feature", + predicateType, + operation, parameters, result, rawResult: null, @@ -35,27 +39,32 @@ export const createApplicationFeatureTraceEvidence = ( }, ); +/** Create derived Evidence for one bounded application-graph feature trace. */ +export const createApplicationFeatureTraceEvidence = ( + subject: EvidenceSubjectTarget | undefined, + parameters: EvidenceObservation["parameters"], + result: ApplicationFeatureTraceResult, +): Evidence => + workflowEvidence( + "rea.application-feature-trace", + "trace_application_feature", + parameters, + result, + subject, + ); + /** Create derived Evidence for one bounded JavaScript semantic trace. */ export const createJavaScriptSemanticTraceEvidence = ( subject: EvidenceSubjectTarget | undefined, parameters: EvidenceObservation["parameters"], result: JavaScriptSemanticTraceResult, ): Evidence => - createEvidence( - subject ?? unknownTarget("derived-from-linked-evidence"), - JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, - { - predicateType: "rea.javascript-semantic-trace", - operation: "trace_javascript_semantics", - parameters, - result, - rawResult: null, - confidence: "inferred", - authority: "analyst-inference", - environment: null, - limitations: result.limitations, - evidenceLinks: result.evidence_links, - }, + workflowEvidence( + "rea.javascript-semantic-trace", + "trace_javascript_semantics", + parameters, + result, + subject, ); /** Create derived Evidence for one tiered application version comparison. */ @@ -63,21 +72,11 @@ export const createApplicationVersionComparisonEvidence = ( parameters: EvidenceObservation["parameters"], result: ApplicationVersionComparisonResult, ): Evidence => - createEvidence( - unknownTarget("derived-from-linked-evidence"), - JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, - { - predicateType: "rea.application-version-comparison", - operation: "compare_application_versions", - parameters, - result, - rawResult: null, - confidence: "inferred", - authority: "analyst-inference", - environment: null, - limitations: result.limitations, - evidenceLinks: result.evidence_links, - }, + workflowEvidence( + "rea.application-version-comparison", + "compare_application_versions", + parameters, + result, ); /** Create derived Evidence for one historical-source to bundle comparison. */ @@ -85,21 +84,11 @@ export const createSourceToBundleComparisonEvidence = ( parameters: EvidenceObservation["parameters"], result: SourceToBundleComparisonResult, ): Evidence => - createEvidence( - unknownTarget("derived-from-linked-evidence"), - JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, - { - predicateType: "rea.source-to-bundle-comparison", - operation: "compare_source_to_bundle", - parameters, - result, - rawResult: null, - confidence: "inferred", - authority: "analyst-inference", - environment: null, - limitations: result.limitations, - evidenceLinks: result.evidence_links, - }, + workflowEvidence( + "rea.source-to-bundle-comparison", + "compare_source_to_bundle", + parameters, + result, ); /** Create derived Evidence for one bounded static export-shape comparison. */ @@ -107,19 +96,9 @@ export const createJavaScriptExportShapeComparisonEvidence = ( parameters: EvidenceObservation["parameters"], result: JavaScriptExportShapeComparisonResult, ): Evidence => - createEvidence( - unknownTarget("derived-from-linked-evidence"), - JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, - { - predicateType: "rea.javascript-export-shape-comparison", - operation: "compare_javascript_export_shapes", - parameters, - result, - rawResult: null, - confidence: "inferred", - authority: "analyst-inference", - environment: null, - limitations: result.limitations, - evidenceLinks: result.evidence_links, - }, + workflowEvidence( + "rea.javascript-export-shape-comparison", + "compare_javascript_export_shapes", + parameters, + result, ); diff --git a/src/browser/CdpObservationSession.ts b/src/browser/CdpObservationSession.ts index f9b8fe85452..eab800166ab 100644 --- a/src/browser/CdpObservationSession.ts +++ b/src/browser/CdpObservationSession.ts @@ -84,7 +84,7 @@ export const observeCdpSession = async ( const capture = new TimelineCapture(allowedOrigins, document, initialUrl); let removeListener = (): void => {}; const removeDisconnectListener = context.connection.onDisconnect(() => - capture.transportDisconnected(), + capture.recordTermination("transport_disconnected"), ); try { await context.connection.send( @@ -274,10 +274,10 @@ class TimelineCapture { this.#lifecycle(registered.payload); return; case "Target.detachedFromTarget": - this.sessionDetached(); + this.recordTermination("session_detached"); return; case "Inspector.targetCrashed": - this.targetTerminated(); + this.recordTermination("target_terminated"); return; default: return; @@ -340,40 +340,18 @@ class TimelineCapture { this.#listeners.clear(); } - targetTerminated(): void { + recordTermination( + reason: "target_terminated" | "session_detached" | "transport_disconnected", + ): void { if (this.#endReason !== undefined) return; this.#add({ - type: "target_terminated", + type: reason, timestamp: null, rawUrl: null, requestId: null, - detail: "target_terminated", + detail: reason, }); - this.end("target_terminated"); - } - - sessionDetached(): void { - if (this.#endReason !== undefined) return; - this.#add({ - type: "session_detached", - timestamp: null, - rawUrl: null, - requestId: null, - detail: "session_detached", - }); - this.end("session_detached"); - } - - transportDisconnected(): void { - if (this.#endReason !== undefined) return; - this.#add({ - type: "transport_disconnected", - timestamp: null, - rawUrl: null, - requestId: null, - detail: "transport_disconnected", - }); - this.end("transport_disconnected"); + this.end(reason); } setFinalUrl(rawUrl: string): void {