#!/bin/zsh -f

# Claude Desktop packaged-main adapter. It plans one fixed-size semantic edit and
# applies only the entry, ASAR JSON header and Info.plist header digest in place.

sc_regular_file_identity() {
	[[ -f "$1" && ! -L "$1" ]] || sc_diagnostic_fail sc_cl_file_invalid
	/usr/bin/stat -f '%d:%i:%z' "$1"
}

sc_write_scalar() {
	print -rn -- "$2" >"$1"
}

sc_read_scalar() {
	[[ -f "$1" && ! -L "$1" ]] || sc_diagnostic_fail sc_cl_plan_incomplete
	REPLY=$(<"$1")
}

sc_count_literal() {
	local source=$1 needle=$2 count=0 remainder=$1
	while [[ "$remainder" == *"$needle"* ]]; do
		remainder=${remainder#*"$needle"}
		(( count += 1 ))
	done
	REPLY=$count
}

sc_extract_json_object() {
	local source=$1 extracted
	[[ "${source[1]}" == '{' ]] || sc_diagnostic_fail sc_cl_asar_meta_invalid
	if ! extracted=$(print -rn -- "$source" | LC_ALL=C /usr/bin/awk '
		BEGIN { RS = "\034"; ORS = ""; depth = 0; quoted = 0; escaped = 0; found = 0 }
		{
			for (i = 1; i <= length($0); i += 1) {
				character = substr($0, i, 1)
				if (quoted) {
					if (escaped) escaped = 0
					else if (character == "\\") escaped = 1
					else if (character == "\"") quoted = 0
					continue
				}
				if (character == "\"") quoted = 1
				else if (character == "{") depth += 1
				else if (character == "}") {
					depth -= 1
					if (depth == 0) {
						print substr($0, 1, i)
						found = 1
						exit
					}
				}
			}
		}
		END { if (!found) exit 1 }
	'); then
		sc_diagnostic_fail sc_cl_asar_meta_truncated
		return
	fi
	REPLY=$extracted
}

sc_parse_entry_metadata() {
	local metadata=$1 hash_lines blocks_source
	[[ "$metadata" =~ '"size":([0-9]+)' ]] || sc_diagnostic_fail sc_cl_asar_size_missing
	sc_entry_size=$match[1]
	[[ "$metadata" =~ '"offset":"([0-9]+)"' ]] || sc_diagnostic_fail sc_cl_asar_offset_missing
	sc_entry_relative_offset=$match[1]
	[[ "$metadata" =~ '"blockSize":([0-9]+)' ]] || sc_diagnostic_fail sc_cl_asar_block_size_missing
	sc_entry_block_size=$match[1]
	[[ "$metadata" =~ '"hash":"([a-f0-9]{64})"' ]] || sc_diagnostic_fail sc_cl_asar_digest_missing
	sc_entry_hash=$match[1]
	[[ "$metadata" == *'"algorithm":"SHA256"'* && "$metadata" == *'"blocks":['* ]] ||
		sc_diagnostic_fail sc_cl_asar_integrity_unsupported
	(( sc_entry_size > 0 && sc_entry_block_size > 0 )) || sc_diagnostic_fail sc_cl_asar_bounds_invalid
	[[ "$metadata" =~ '"blocks":\[([^]]*)\]' ]] || sc_diagnostic_fail sc_cl_asar_blocks_missing
	blocks_source=$match[1]
	hash_lines=$(print -rn -- "$blocks_source" | /usr/bin/grep -aoE '[a-f0-9]{64}' || true)
	sc_entry_block_hashes=("${(@f)hash_lines}")
	(( ${#sc_entry_block_hashes} == (sc_entry_size + sc_entry_block_size - 1) / sc_entry_block_size )) ||
		sc_diagnostic_fail sc_cl_asar_block_count_invalid
}

sc_hash_entry_blocks() {
	local file=$1 block_size=$2 block_count=$3 index digest
	REPLY=()
	for (( index = 0; index < block_count; index += 1 )); do
		digest=$(/bin/dd if="$file" bs="$block_size" skip="$index" count=1 2>/dev/null |
			/usr/bin/openssl dgst -sha256 | /usr/bin/awk '{print $NF}')
		[[ "$digest" == [a-f0-9]## ]] || sc_diagnostic_fail sc_cl_asar_block_hash_failed
		REPLY+=("$digest")
	done
}

sc_patch_entry() {
	local native=$1 patched=$2 bootstrap_namespace=$3 declaration_output suffix_output declaration offset identifier hook
	local marker_offset suffix_offset prior_byte middle_bytes budget patched_size
	[[ "$(/usr/bin/head -c 13 "$native")" == '"use strict";' ]] || sc_diagnostic_fail sc_cl_main_prefix_missing
	/usr/bin/iconv -f UTF-8 -t UTF-8 "$native" >"$sc_stage/entry.utf8"
	/usr/bin/cmp -s "$native" "$sc_stage/entry.utf8" || sc_diagnostic_fail sc_cl_main_utf8_invalid
	declaration_output=$(/usr/bin/grep -aEbo 'let [A-Za-z_$][A-Za-z0-9_$]*=require\("node:os"\);' "$native" || true)
	sc_declaration_matches=("${(@f)declaration_output}")
	if (( ${#sc_declaration_matches} == 0 )); then
		sc_diagnostic_fail sc_cl_bootstrap_anchor_missing
		return
	elif (( ${#sc_declaration_matches} != 1 )); then
		sc_diagnostic_fail sc_cl_bootstrap_anchor_ambiguous
		return
	fi
	declaration=$sc_declaration_matches[1]
	offset=${declaration%%:*}
	declaration=${declaration#*:}
	identifier=${declaration#let }
	identifier=${identifier%%=*}
	(( offset += ${#declaration} ))
	[[ "$bootstrap_namespace" == .s || "$bootstrap_namespace" == .d || "$bootstrap_namespace" == .e ]] ||
		sc_diagnostic_fail sc_cl_namespace_unsupported
	hook="try{require(${identifier}.homedir()+\"/$bootstrap_namespace\")}catch{}"

	suffix_output=$(/usr/bin/grep -aEbo '//# sourceMappingURL=[^[:cntrl:]]+' "$native" || true)
	sc_suffix_matches=("${(@f)suffix_output}")
	if (( ${#sc_suffix_matches} == 0 )); then
		sc_diagnostic_fail sc_cl_sourcemap_missing
		return
	elif (( ${#sc_suffix_matches} != 1 )); then
		sc_diagnostic_fail sc_cl_sourcemap_ambiguous
		return
	fi
	marker_offset=${sc_suffix_matches[1]%%:*}
	[[ "$(/usr/bin/tail -n 1 "$native")" == '//# sourceMappingURL='* ]] || sc_diagnostic_fail sc_cl_sourcemap_not_final
	suffix_offset=$marker_offset
	if (( marker_offset > 0 )); then
		prior_byte=$(/bin/dd if="$native" bs=1 skip="$((marker_offset - 1))" count=1 2>/dev/null | /usr/bin/od -An -tu1)
		prior_byte=${prior_byte//[[:space:]]/}
		if [[ "$prior_byte" == 10 ]]; then
			(( suffix_offset -= 1 ))
			if (( suffix_offset > 0 )); then
				prior_byte=$(/bin/dd if="$native" bs=1 skip="$((suffix_offset - 1))" count=1 2>/dev/null | /usr/bin/od -An -tu1)
				prior_byte=${prior_byte//[[:space:]]/}
				[[ "$prior_byte" == 13 ]] && (( suffix_offset -= 1 ))
			fi
		fi
	fi
	(( offset <= suffix_offset )) || sc_diagnostic_fail sc_cl_anchor_order_invalid
	middle_bytes=$((suffix_offset - offset))
	budget=$((sc_entry_size - offset - ${#hook} - middle_bytes - 1))
	(( budget >= 0 )) || sc_diagnostic_fail sc_cl_patch_space_insufficient
	{
		/usr/bin/head -c "$offset" "$native"
		print -rn -- "$hook"
		/usr/bin/head -c "$suffix_offset" "$native" | /usr/bin/tail -c "$middle_bytes"
		(( budget > 0 )) && printf '%*s' "$budget" ''
		printf '\n'
	} >"$patched"
	patched_size=$(/usr/bin/stat -f '%z' "$patched")
	(( patched_size == sc_entry_size )) || sc_diagnostic_fail sc_cl_patched_size_changed
}

sc_patch_header() {
	local header=$1 patched=$2 before=$3 metadata=$4 after=$5 native_blocks next_metadata
	local old_blocks new_blocks index integrity_key metadata_prefix native_integrity patched_integrity segment
	native_blocks='"blocks":['
	new_blocks='"blocks":['
	for (( index = 1; index <= ${#sc_entry_block_hashes}; index += 1 )); do
		(( index > 1 )) && { native_blocks+=','; new_blocks+=','; }
		native_blocks+='"'$sc_entry_block_hashes[index]'"'
		new_blocks+='"'$sc_patched_block_hashes[index]'"'
	done
	native_blocks+=']'
	new_blocks+=']'
	sc_count_literal "$metadata" '"hash":"'$sc_entry_hash'"'
	(( REPLY == 1 )) || sc_diagnostic_fail sc_cl_digest_field_ambiguous
	sc_count_literal "$metadata" "$native_blocks"
	(( REPLY == 1 )) || sc_diagnostic_fail sc_cl_blocks_field_ambiguous
	next_metadata=${metadata/'"hash":"'$sc_entry_hash'"'/'"hash":"'$sc_patched_entry_hash'"'}
	next_metadata=${next_metadata/"$native_blocks"/"$new_blocks"}
	print -rn -- "$before$next_metadata$after" >"$patched"
	[[ $(/usr/bin/stat -f '%z' "$header") == $(/usr/bin/stat -f '%z' "$patched") ]] || sc_diagnostic_fail sc_cl_header_size_changed
	integrity_key='"integrity":'
	[[ "$metadata" == *"$integrity_key"* ]] || sc_diagnostic_fail sc_cl_integrity_object_missing
	metadata_prefix=${metadata%%"$integrity_key"*}$integrity_key
	sc_extract_json_object "${metadata#*"$integrity_key"}"; native_integrity=$REPLY
	sc_extract_json_object "${next_metadata#*"$integrity_key"}"; patched_integrity=$REPLY
	[[ ${#native_integrity} == ${#patched_integrity} ]] || sc_diagnostic_fail sc_cl_integrity_size_changed
	segment=${header%.native}-integrity
	print -rn -- "$native_integrity" >"$segment.native"
	print -rn -- "$patched_integrity" >"$segment.patched"
	sc_write_scalar "$segment-offset" "$(( ${#before} + ${#metadata_prefix} ))"
	sc_write_scalar "$segment-size" "${#native_integrity}"
}

sc_patch_plist() {
	local native=$1 patched=$2 old_hash=$3 new_hash=$4 occurrences offset
	/usr/bin/grep -aqF '<key>ElectronAsarIntegrity</key>' "$native" || sc_diagnostic_fail sc_cl_plist_integrity_missing
	occurrences=$(/usr/bin/grep -aoF "$old_hash" "$native" | /usr/bin/wc -l | /usr/bin/tr -d ' ')
	if [[ "$occurrences" == 0 ]]; then
		sc_diagnostic_fail sc_cl_plist_digest_missing
		return
	elif [[ "$occurrences" != 1 ]]; then
		sc_diagnostic_fail sc_cl_plist_digest_ambiguous
		return
	fi
	offset=$(/usr/bin/grep -aboF "$old_hash" "$native")
	offset=${offset%%:*}
	sc_plist_asar_integrity_offset=$offset
	/bin/cp -p "$native" "$patched"
	print -rn -- "$new_hash" | /bin/dd of="$patched" bs=1 seek="$offset" conv=notrunc 2>/dev/null
	[[ $(/usr/bin/stat -f '%z' "$native") == $(/usr/bin/stat -f '%z' "$patched") ]] || sc_diagnostic_fail sc_cl_plist_size_changed
}

sc_asar_plan() {
	local app=$1 stage=$2 runtime_version=$3 bootstrap_namespace=${4:-.s} asar plist prefix_bytes header_size json_size content_offset
	local entry_key entry_matches entry_offset metadata_offset prefix remainder metadata after asar_size old_header_hash new_header_hash index
	local actual_hash
	app=${app:A}
	asar="$app/Contents/Resources/app.asar"
	plist="$app/Contents/Info.plist"
	[[ "$(/usr/bin/plutil -extract CFBundleIdentifier raw "$plist")" == com.anthropic.claudefordesktop ]] ||
		sc_diagnostic_fail sc_cl_bundle_invalid
	/usr/bin/plutil -lint "$plist" >/dev/null
	prefix_bytes=$(/usr/bin/od -An -tu1 -N16 "$asar")
	sc_prefix=( ${(z)prefix_bytes} )
	(( ${#sc_prefix} == 16 )) || sc_diagnostic_fail sc_cl_asar_prefix_unreadable
	(( sc_prefix[1] + sc_prefix[2] * 256 + sc_prefix[3] * 65536 + sc_prefix[4] * 16777216 == 4 )) ||
		sc_diagnostic_fail sc_cl_asar_prefix_unsupported
	header_size=$((sc_prefix[5] + sc_prefix[6] * 256 + sc_prefix[7] * 65536 + sc_prefix[8] * 16777216))
	json_size=$((sc_prefix[13] + sc_prefix[14] * 256 + sc_prefix[15] * 65536 + sc_prefix[16] * 16777216))
	(( json_size >= 2 && json_size <= 32 * 1024 * 1024 && header_size >= json_size + 8 )) || sc_diagnostic_fail sc_cl_asar_header_bounds_invalid
	content_offset=$((8 + header_size))
	/bin/dd if="$asar" of="$stage/header.native" bs=1 skip=16 count="$json_size" 2>/dev/null
	/usr/bin/plutil -convert xml1 -o /dev/null "$stage/header.native"
	[[ $(/usr/bin/stat -f '%z' "$stage/header.native") == "$json_size" ]] || sc_diagnostic_fail sc_cl_asar_header_incomplete
	entry_key='"index.pre.js":'
	entry_matches=$(/usr/bin/grep -aboF "$entry_key" "$stage/header.native" || true)
	sc_entry_matches=("${(@f)entry_matches}")
	if (( ${#sc_entry_matches} == 0 )); then
		sc_diagnostic_fail sc_cl_main_entry_missing
		return
	elif (( ${#sc_entry_matches} != 1 )); then
		sc_diagnostic_fail sc_cl_main_entry_ambiguous
		return
	fi
	entry_offset=${sc_entry_matches[1]%%:*}
	[[ "$entry_offset" == <-> ]] || sc_diagnostic_fail sc_cl_asar_meta_invalid
	metadata_offset=$((entry_offset + ${#entry_key}))
	prefix=$(/usr/bin/head -c "$metadata_offset" "$stage/header.native")
	remainder=$(/usr/bin/tail -c "+$((metadata_offset + 1))" "$stage/header.native")
	sc_extract_json_object "$remainder"
	metadata=$REPLY
	after=${remainder[${#metadata}+1,-1]}
	print -rn -- "$metadata" >"$stage/entry-metadata.native"
	sc_parse_entry_metadata "$metadata"
	(( sc_entry_relative_offset >= 0 )) || sc_diagnostic_fail sc_cl_entry_offset_invalid
	sc_entry_absolute_offset=$((content_offset + sc_entry_relative_offset))
	asar_size=$(/usr/bin/stat -f '%z' "$asar")
	(( sc_entry_absolute_offset + sc_entry_size <= asar_size )) || sc_diagnostic_fail sc_cl_entry_out_of_bounds
	/usr/bin/head -c "$((sc_entry_absolute_offset + sc_entry_size))" "$asar" | /usr/bin/tail -c "$sc_entry_size" >"$stage/entry.native"
	actual_hash=$(sc_sha256_file "$stage/entry.native")
	[[ "$actual_hash" == "$sc_entry_hash" ]] || sc_diagnostic_fail sc_cl_entry_digest_mismatch
	sc_hash_entry_blocks "$stage/entry.native" "$sc_entry_block_size" "${#sc_entry_block_hashes}"
	[[ "${(j:\n:)REPLY}" == "${(j:\n:)sc_entry_block_hashes}" ]] || sc_diagnostic_fail sc_cl_entry_blocks_mismatch

	sc_patch_entry "$stage/entry.native" "$stage/entry.patched" "$bootstrap_namespace"
	sc_patched_entry_hash=$(sc_sha256_file "$stage/entry.patched")
	sc_hash_entry_blocks "$stage/entry.patched" "$sc_entry_block_size" "${#sc_entry_block_hashes}"
	sc_patched_block_hashes=("${REPLY[@]}")
	sc_patch_header "$stage/header.native" "$stage/header.patched" "$prefix" "$metadata" "$after"
	old_header_hash=$(sc_sha256_file "$stage/header.native")
	new_header_hash=$(sc_sha256_file "$stage/header.patched")
	/bin/cp -p "$plist" "$stage/plist.native"
	sc_patch_plist "$stage/plist.native" "$stage/plist.patched" "$old_header_hash" "$new_header_hash"
	/bin/dd if="$stage/plist.native" of="$stage/plist-asar-integrity.native" bs=1 skip="$sc_plist_asar_integrity_offset" count=64 2>/dev/null
	/bin/dd if="$stage/plist.patched" of="$stage/plist-asar-integrity.patched" bs=1 skip="$sc_plist_asar_integrity_offset" count=64 2>/dev/null

	sc_write_scalar "$stage/asar-identity" "$(sc_regular_file_identity "$asar")"
	sc_write_scalar "$stage/plist-identity" "$(sc_regular_file_identity "$plist")"
	sc_write_scalar "$stage/asar-pristine-sha256" "$(sc_sha256_file "$asar")"
	sc_write_scalar "$stage/plist-pristine-sha256" "$(sc_sha256_file "$plist")"
	sc_write_scalar "$stage/entry-offset" "$sc_entry_absolute_offset"
	sc_write_scalar "$stage/entry-size" "$sc_entry_size"
	sc_write_scalar "$stage/header-size" "$json_size"
	sc_write_scalar "$stage/plist-asar-integrity-offset" "$sc_plist_asar_integrity_offset"
	sc_write_scalar "$stage/entry-patched-sha256" "$(sc_sha256_file "$stage/entry.patched")"
	sc_write_scalar "$stage/header-patched-sha256" "$(sc_sha256_file "$stage/header.patched")"
	sc_write_scalar "$stage/plist-patched-sha256" "$(sc_sha256_file "$stage/plist.patched")"
	sc_write_scalar "$stage/desktop-version" "$(/usr/bin/plutil -extract CFBundleShortVersionString raw "$plist")"
	sc_write_scalar "$stage/bundle-version" "$(/usr/bin/plutil -extract CFBundleVersion raw "$plist")"
	sc_write_scalar "$stage/runtime-version" "$runtime_version"
}

sc_manifest_source() {
	local app=$1 stage=$2 asar=$3 plist=$4 installed_at=$5
	local desktop_version bundle_version runtime_version asar_pristine plist_pristine asar_patched plist_patched
	local entry_offset entry_size header_size header_integrity_offset header_integrity_size plist_integrity_offset
	sc_read_scalar "$stage/desktop-version"; desktop_version=$REPLY
	sc_read_scalar "$stage/bundle-version"; bundle_version=$REPLY
	sc_read_scalar "$stage/runtime-version"; runtime_version=$REPLY
	sc_read_scalar "$stage/asar-pristine-sha256"; asar_pristine=$REPLY
	sc_read_scalar "$stage/plist-pristine-sha256"; plist_pristine=$REPLY
	sc_read_scalar "$stage/entry-offset"; entry_offset=$REPLY
	sc_read_scalar "$stage/entry-size"; entry_size=$REPLY
	sc_read_scalar "$stage/header-size"; header_size=$REPLY
	sc_read_scalar "$stage/header-integrity-offset"; header_integrity_offset=$((REPLY + 16))
	sc_read_scalar "$stage/header-integrity-size"; header_integrity_size=$REPLY
	sc_read_scalar "$stage/plist-asar-integrity-offset"; plist_integrity_offset=$REPLY
	asar_patched=$(sc_sha256_file "$asar")
	plist_patched=$(sc_sha256_file "$plist")
	sc_json_string "$app"; local app_json=$REPLY
	sc_json_string "$desktop_version"; local desktop_json=$REPLY
	sc_json_string "$bundle_version"; local bundle_json=$REPLY
	sc_json_string "$runtime_version"; local runtime_json=$REPLY
	cat <<EOF
{
  "schemaVersion": 1,
  "appPath": $app_json,
  "bundleIdentifier": "com.anthropic.claudefordesktop",
  "desktopVersion": $desktop_json,
  "bundleVersion": $bundle_json,
  "entryPath": ".vite/build/index.pre.js",
  "installedAt": "$installed_at",
  "runtimeVersion": $runtime_json,
	  "resources": {
	    "asar": { "bytes": $(/usr/bin/stat -f '%z' "$asar"), "pristineSha256": "$asar_pristine", "patchedSha256": "$asar_patched" },
	    "infoPlist": { "bytes": $(/usr/bin/stat -f '%z' "$plist"), "pristineSha256": "$plist_pristine", "patchedSha256": "$plist_patched" }
	  },
	  "sealedResourcePatch": {
	    "asarEntry": { "offset": $entry_offset, "bytes": $entry_size, "pristineSha256": "$(sc_sha256_file "$stage/entry.native")", "patchedSha256": "$(sc_sha256_file "$stage/entry.patched")" },
	    "asarEntryIntegrity": { "offset": $header_integrity_offset, "bytes": $header_integrity_size, "pristineSha256": "$(sc_sha256_file "$stage/header-integrity.native")", "patchedSha256": "$(sc_sha256_file "$stage/header-integrity.patched")" },
	    "asarHeader": { "offset": 16, "bytes": $header_size, "pristineSha256": "$(sc_sha256_file "$stage/header.native")", "patchedSha256": "$(sc_sha256_file "$stage/header.patched")" },
	    "infoPlistAsarIntegrity": { "offset": $plist_integrity_offset, "bytes": 64, "pristineSha256": "$(sc_sha256_file "$stage/plist-asar-integrity.native")", "patchedSha256": "$(sc_sha256_file "$stage/plist-asar-integrity.patched")" }
	  }
}
EOF
}

sc_transfer_file_to_fd() {
	local source=$1 output_fd=$2 output_offset=$3 expected_bytes=$4 input_fd transferred transfer_status
	local transferred_bytes=0
	sysseek -u "$output_fd" "$output_offset" || return
	exec {input_fd}<"$source" || return
	while true; do
		if sysread -i "$input_fd" -o "$output_fd" -s 1048576 -c transferred; then
			(( transferred_bytes += transferred ))
		else
			transfer_status=$?
			break
		fi
	done
	exec {input_fd}<&-
	(( transfer_status == 5 && transferred_bytes == expected_bytes ))
}

sc_asar_apply() {
	local app=${1:A} stage=$2 manifest_path=$3 asar plist expected_asar_identity expected_plist_identity
	local expected_asar_hash expected_plist_hash entry_offset entry_size asar_fd plist_fd installed_at
	local expected_entry_patch expected_header_patch expected_plist_patch
	local header_integrity_offset header_integrity_size plist_integrity_offset
	local failure=''
	asar="$app/Contents/Resources/app.asar"
	plist="$app/Contents/Info.plist"
	sc_read_scalar "$stage/asar-identity"; expected_asar_identity=$REPLY
	sc_read_scalar "$stage/plist-identity"; expected_plist_identity=$REPLY
	sc_read_scalar "$stage/asar-pristine-sha256"; expected_asar_hash=$REPLY
	sc_read_scalar "$stage/plist-pristine-sha256"; expected_plist_hash=$REPLY
	sc_read_scalar "$stage/entry-offset"; entry_offset=$REPLY
	sc_read_scalar "$stage/entry-size"; entry_size=$REPLY
	sc_read_scalar "$stage/header-integrity-offset"; header_integrity_offset=$((REPLY + 16))
	sc_read_scalar "$stage/header-integrity-size"; header_integrity_size=$REPLY
	sc_read_scalar "$stage/plist-asar-integrity-offset"; plist_integrity_offset=$REPLY
	sc_read_scalar "$stage/entry-patched-sha256"; expected_entry_patch=$REPLY
	sc_read_scalar "$stage/header-patched-sha256"; expected_header_patch=$REPLY
	sc_read_scalar "$stage/plist-patched-sha256"; expected_plist_patch=$REPLY
	[[ "$(sc_sha256_file "$stage/entry.patched")" == "$expected_entry_patch" &&
		"$(sc_sha256_file "$stage/header.patched")" == "$expected_header_patch" &&
		"$(sc_sha256_file "$stage/plist.patched")" == "$expected_plist_patch" ]] || sc_diagnostic_fail sc_cl_patch_plan_changed
	[[ "$(sc_regular_file_identity "$asar")" == "$expected_asar_identity" && "$(sc_regular_file_identity "$plist")" == "$expected_plist_identity" ]] ||
		sc_diagnostic_fail sc_cl_resources_replaced
	[[ "$(sc_sha256_file "$asar")" == "$expected_asar_hash" && "$(sc_sha256_file "$plist")" == "$expected_plist_hash" ]] ||
		sc_diagnostic_fail sc_cl_resources_changed
	zmodload zsh/system
	exec {asar_fd}<>"$asar"
	exec {plist_fd}<>"$plist"
	if [[ "$(/usr/bin/stat -f '%i:%z' "/dev/fd/$asar_fd")" != "${expected_asar_identity#*:}" ||
		"$(/usr/bin/stat -f '%i:%z' "/dev/fd/$plist_fd")" != "${expected_plist_identity#*:}" ]]; then
		failure=sc_cl_resources_changed_on_open
	else
		if ! sc_transfer_file_to_fd "$stage/entry.patched" "$asar_fd" "$entry_offset" "$entry_size"; then
			failure=sc_cl_main_write_failed
		fi
		[[ ${SUPERCODE_CLAUDE_INSTALL_FAULT:-} != after-entry ]] || failure=sc_cl_test_fault
		if [[ -z "$failure" ]]; then
			if ! sc_transfer_file_to_fd "$stage/header-integrity.patched" "$asar_fd" "$header_integrity_offset" "$header_integrity_size"; then
				failure=sc_cl_integrity_write_failed
			fi
			[[ ${SUPERCODE_CLAUDE_INSTALL_FAULT:-} != after-header ]] || failure=sc_cl_test_fault
		fi
		if [[ -z "$failure" ]]; then
			if ! sc_transfer_file_to_fd "$stage/plist-asar-integrity.patched" "$plist_fd" "$plist_integrity_offset" 64; then
				failure=sc_cl_plist_write_failed
			fi
			[[ ${SUPERCODE_CLAUDE_INSTALL_FAULT:-} != after-plist ]] || failure=sc_cl_test_fault
		fi
		/bin/sync
		if [[ -z "$failure" ]]; then
			[[ "$(sc_regular_file_identity "$asar")" == "$expected_asar_identity" && "$(sc_regular_file_identity "$plist")" == "$expected_plist_identity" ]] ||
				failure=sc_cl_resources_replaced_during_patch
		fi
		if [[ -z "$failure" ]]; then
			if ! /usr/bin/head -c "$((entry_offset + entry_size))" "$asar" | /usr/bin/tail -c "$entry_size" >"$stage/entry.readback" ||
				! /bin/dd if="$asar" of="$stage/header-integrity.readback" bs=1 skip="$header_integrity_offset" count="$header_integrity_size" 2>/dev/null ||
				! /bin/dd if="$plist" of="$stage/plist-asar-integrity.readback" bs=1 skip="$plist_integrity_offset" count=64 2>/dev/null; then
				failure=sc_cl_readback_failed
			fi
		fi
		if [[ -z "$failure" ]]; then
			/usr/bin/cmp -s "$stage/entry.patched" "$stage/entry.readback" || failure=sc_cl_main_readback_mismatch
			/usr/bin/cmp -s "$stage/header-integrity.patched" "$stage/header-integrity.readback" ||
				failure=sc_cl_integrity_readback_mismatch
			/usr/bin/cmp -s "$stage/plist-asar-integrity.patched" "$stage/plist-asar-integrity.readback" ||
				failure=sc_cl_plist_readback_mismatch
		fi
	fi
	if [[ -z "$failure" ]]; then
		installed_at=$(/bin/date -u '+%Y-%m-%dT%H:%M:%SZ')
		if ! sc_manifest_source "$app" "$stage" "$asar" "$plist" "$installed_at" >"$stage/installed.json"; then
			failure=sc_cl_manifest_build_failed
		elif ! /usr/bin/plutil -convert xml1 -o /dev/null "$stage/installed.json"; then
			failure=sc_cl_manifest_invalid
		elif [[ ${SUPERCODE_CLAUDE_INSTALL_FAULT:-} == before-manifest ]]; then
			failure=sc_cl_test_fault
		elif ! sc_copy_atomic "$stage/installed.json" "$manifest_path"; then
			failure=sc_cl_manifest_publish_failed
		fi
	fi
	if [[ -n "$failure" ]]; then
		sc_transfer_file_to_fd "$stage/entry.native" "$asar_fd" "$entry_offset" "$entry_size" || true
		sc_transfer_file_to_fd "$stage/header-integrity.native" "$asar_fd" "$header_integrity_offset" "$header_integrity_size" || true
		sc_transfer_file_to_fd "$stage/plist-asar-integrity.native" "$plist_fd" "$plist_integrity_offset" 64 || true
		/bin/sync
		exec {asar_fd}>&-
		exec {plist_fd}>&-
		[[ "$(sc_sha256_file "$asar")" == "$expected_asar_hash" && "$(sc_sha256_file "$plist")" == "$expected_plist_hash" ]] ||
			sc_diagnostic_fail sc_cl_rollback_failed
		sc_diagnostic_fail "$failure"
	fi
	exec {asar_fd}>&-
	exec {plist_fd}>&-
}
