<?xml version='1.0' encoding='utf-8'?>
<CheatTable CheatEngineTableVersion="45">
  <CheatEntries>
    <CheatEntry>
      <ID>1000</ID>
      <Description>"Ersatz MGS Master Collection Cheat Table - Created with OpenAI CODEX"</Description>
      <IsGroupHeader>1</IsGroupHeader>
    </CheatEntry>
    <CheatEntry>
      <ID>200</ID>
      <Description>"MGS"</Description>
      <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Open this game section without enabling any codes.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
local a=getAddressList()
for _,id in ipairs({15,12,10,11,100,4,13,3,2,5,6,8,1,7,9})do
 local r=a.getMemoryRecordByID(id)
 if r and r.Active then r.Active=false;assert(not r.Active,"Could not stop "..r.Description)end
end
{$asm}
</AssemblerScript>
      <CheatEntries>
        <CheatEntry>
          <ID>2</ID>
          <Description>"Health protection + heal (jeep / rappel)"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'mgs-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
MGSTableDir=dir
local t=dofile(MGSTableDir..'mgs-toggles.lua');t.enable('health')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSToggles then local ok,err=MGSToggles.disable('health');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>3</ID>
          <Description>"Unlimited ammo + grenades - tested SOCOM/grenades"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'mgs-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
MGSTableDir=dir
local t=dofile(MGSTableDir..'mgs-toggles.lua');t.enable('ammo')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSToggles then local ok,err=MGSToggles.disable('ammo');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>13</ID>
          <Description>"Infinite O2 - gas / underwater"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'mgs-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
MGSTableDir=dir
dofile(MGSTableDir..'mgs-oxygen.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSOxygen then MGSOxygen.disable()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>4</ID>
          <Description>"No alert - guards + cameras (automatic area binding)"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'mgs-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
MGSTableDir=dir
local p=dofile(MGSTableDir..'mgs-no-alert.lua');p.enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSNoAlert then local ok,err=MGSNoAlert.disable();assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>5</ID>
          <Description>"Weapon &amp; gadget selector - grant any equipment"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'mgs-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
MGSTableDir=dir
local p=dofile(MGSTableDir..'inventory-panel.lua');p.show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSInventoryPanel then MGSInventoryPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>6</ID>
          <Description>"Game statistics editor - rank counters + play time"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'mgs-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
MGSTableDir=dir
local p=dofile(MGSTableDir..'statistics-panel.lua');p.show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSStatisticsPanel then MGSStatisticsPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>8</ID>
          <Description>"Defeat current boss (Ocelot tested)"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'boss-panel.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
local a=dofile(dir..'mgs-boss-actions.lua');a.defeatCurrentBoss()
local timer=createTimer(nil,false);timer.Interval=100;timer.OnTimer=function()
 timer.Enabled=false;timer.destroy();local r=getAddressList().getMemoryRecordByID(8)
 if r and r.Description:match('^Defeat current boss')and r.Active then r.Active=false end end;timer.Enabled=true
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
-- One-shot action; normal gameplay handles the defeat sequence.
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>10</ID>
          <Description>"Proximity auto knockout - guards near Snake"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'boss-panel.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
local p=dofile(dir..'mgs-guard-proximity.lua');p.enable('knockout')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSGuardProximity then MGSGuardProximity.disable('knockout')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>11</ID>
          <Description>"Proximity auto kill - guards near Snake"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'boss-panel.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
local p=dofile(dir..'mgs-guard-proximity.lua');p.enable('kill')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSGuardProximity then MGSGuardProximity.disable('kill')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>12</ID>
          <Description>"Room &amp; encounter loader"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
MGSTableDir=dir
dofile(dir..'room-loader-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSRoomPanel then MGSRoomPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>100</ID>
          <Description>"Debugging - dashboards and guard state"</Description>
          <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
          <Color>0000FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Reveal diagnostic entries; opening the section does not activate them.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({1,7,9})do local r=getAddressList().getMemoryRecordByID(id)
 if r and r.Active then r.Active=false end end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>1</ID>
              <Description>"Dashboard / recorder (F7)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
if not MGSDashboard then
 local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
 if not dir then
  local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
  if ok and type(path)=='string' and path:lower():match('metal%-gear%-solid.*%.ct$')then
   local candidate=path:match('^(.*[\\/])')
   if candidate then local f=io.open(candidate..'dashboard.lua','r');if f then f:close();dir=candidate end end
  end
 end
 assert(dir,'Open the CT from its extracted Table folder')
 MGSTableDir=dir
 dofile(dir..'dashboard.lua')
end
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSDashboard then local ok,err=MGSDashboard.stop();assert(ok,err)end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
            <CheatEntry>
              <ID>7</ID>
              <Description>"Boss dashboard - read-only observer + recorder"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'boss-panel.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
local p=dofile(dir..'boss-panel.lua');p.show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSBossDashboard then MGSBossDashboard.stop()end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
            <CheatEntry>
              <ID>9</ID>
              <Description>"Guard state - kill / knock out loaded guards"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string' then local candidate=path:match('^(.*[\\/])')
  if candidate then local f=io.open(candidate..'boss-panel.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
local p=dofile(dir..'guard-state-panel.lua');p.show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSGuardStatePanel then MGSGuardStatePanel.stop()end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>15</ID>
          <Description>"Fun stuff"</Description>
          <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Open the menu without enabling effects.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({14,16,17,18,19})do local r=getAddressList().getMemoryRecordByID(id)
 if r and r.Active then r.Active=false;assert(not r.Active,"Could not stop "..r.Description)end end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>14</ID>
              <Description>"Super Saiyan Snake - rainbow + orbiting sparkles"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
MGSTableDir=dir
for _,id in ipairs({17,18,19})do local r=getAddressList().getMemoryRecordByID(id)
 if r and r.Active then r.Active=false;assert(not r.Active,"Could not stop "..r.Description)end end
dofile(dir..'mgs-super-saiyan.lua').start({speed=false,hover=false})
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSSuperSaiyan then MGSSuperSaiyan.stop()end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>16</ID>
              <Description>"Big head - 1.8x"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
MGSTableDir=dir
dofile(dir..'mgs-fun-stuff.lua').enable('head')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSFunStuff then MGSFunStuff.disable('head')end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>17</ID>
              <Description>"Red suit"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
MGSTableDir=dir
for _,id in ipairs({14,18,19})do local r=getAddressList().getMemoryRecordByID(id)
 if r and r.Active then r.Active=false;assert(not r.Active,"Could not stop "..r.Description)end end
dofile(dir..'mgs-fun-stuff.lua').enable('red')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSFunStuff then MGSFunStuff.disable('red')end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>18</ID>
              <Description>"Green suit"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
MGSTableDir=dir
for _,id in ipairs({14,17,19})do local r=getAddressList().getMemoryRecordByID(id)
 if r and r.Active then r.Active=false;assert(not r.Active,"Could not stop "..r.Description)end end
dofile(dir..'mgs-fun-stuff.lua').enable('green')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSFunStuff then MGSFunStuff.disable('green')end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>19</ID>
              <Description>"Black suit"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.mgs
MGSTableDir=dir
for _,id in ipairs({14,17,18})do local r=getAddressList().getMemoryRecordByID(id)
 if r and r.Active then r.Active=false;assert(not r.Active,"Could not stop "..r.Description)end end
dofile(dir..'mgs-fun-stuff.lua').enable('black')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if MGSFunStuff then MGSFunStuff.disable('black')end
{$asm}
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>300</ID>
      <Description>"VR Missions"</Description>
      <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Open this section without enabling gameplay features.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({314,313,312,310,311,400,304,303,302,305,301,309})do
 local row=getAddressList().getMemoryRecordByID(id)
 if row and row.Active then row.Active=false;assert(not row.Active,'Could not stop '..row.Description)end
end
{$asm}
</AssemblerScript>
      <CheatEntries>
        <CheatEntry>
          <ID>302</ID>
          <Description>"Health protection + heal - VR"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-toggles.lua').enable('health')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMToggles then local ok,err=VRMToggles.disable('health');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>303</ID>
          <Description>"Unlimited owned ammo + grenades - VR"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-toggles.lua').enable('ammo')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMToggles then local ok,err=VRMToggles.disable('ammo');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>304</ID>
          <Description>"No alert - recognized VR guards/cameras"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-no-alert.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMNoAlert then local ok,err=VRMNoAlert.disable();assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>305</ID>
          <Description>"Weapon &amp; gadget selector - VR"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'inventory-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMInventoryPanel then VRMInventoryPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>312</ID>
          <Description>"Advanced + Special access - no fake clears"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-unlocks.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMUnlocks then local ok,err=VRMUnlocks.disable();assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>314</ID>
          <Description>"Freeze mission countdown - dynamic VR timer"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-timer.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMTimer then VRMTimer.disable()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>313</ID>
          <Description>"Auto-clear current mission - one-shot"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
local M=dofile(dir..'vrm-mission-clear.lua');M.apply()
local timer=createTimer(nil,false);timer.Interval=100
timer.OnTimer=function()timer.Enabled=false;timer.destroy();local r=getAddressList().getMemoryRecordByID(313);if r and r.Active then r.Active=false end end
timer.Enabled=true
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
-- One-shot clear cannot be undone by unchecking; no persistent controller.
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>310</ID>
          <Description>"Proximity auto knockout - VR"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-guard-proximity.lua').enable('knockout')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMGuardProximity then VRMGuardProximity.disable('knockout')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>311</ID>
          <Description>"Proximity auto kill - VR"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'vrm-guard-proximity.lua').enable('kill')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMGuardProximity then VRMGuardProximity.disable('kill')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>400</ID>
          <Description>"Debugging - VR monitor and guard actions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
-- Reveal children only.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({301,309})do local r=getAddressList().getMemoryRecordByID(id);if r and r.Active then r.Active=false end end
{$asm}
</AssemblerScript>
          <Color>0000FF</Color>
          <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
          <CheatEntries>
            <CheatEntry>
              <ID>301</ID>
              <Description>"Dashboard / recorder (F7) - VR read-only"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
if not VRMDashboard then dofile(dir..'dashboard.lua')end
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMDashboard then assert(VRMDashboard.stop())end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
            <CheatEntry>
              <ID>309</ID>
              <Description>"Guard state - VR knockout / kill"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.vr
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'VR-Missions/';local f=io.open(candidate..'vrm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
VRMTableDir=dir
dofile(dir..'guard-state-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if VRMGuardStatePanel then VRMGuardStatePanel.stop()end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>500</ID>
      <Description>"Integral"</Description>
      <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Reveal Integral's independent, initially-off controls.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({513,510,511,504,503,502,505,506,512,508,507,501,509,600})do
 local row=getAddressList().getMemoryRecordByID(id)
 if row and row.Active then row.Active=false;assert(not row.Active,'Could not stop '..row.Description)end
end
{$asm}
</AssemblerScript>
      <CheatEntries>
        <CheatEntry>
          <ID>502</ID>
          <Description>"Health protection + heal (jeep / rappel) - Integral"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'int-toggles.lua').enable('health')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTToggles then local ok,err=INTToggles.disable('health');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>513</ID>
          <Description>"Torture health refill - automatic rounds"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'int-torture-health.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTTortureHealth then INTTortureHealth.stop('Disabled by user')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>503</ID>
          <Description>"Unlimited owned ammo + grenades - automatic area binding"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'int-toggles.lua').enable('ammo')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTToggles then local ok,err=INTToggles.disable('ammo');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>504</ID>
          <Description>"No alert - recognized Integral guards/cameras"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'int-no-alert.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTNoAlert then local ok,err=INTNoAlert.disable();assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>505</ID>
          <Description>"Weapon &amp; gadget selector - Integral"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'inventory-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTInventoryPanel then INTInventoryPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>506</ID>
          <Description>"Game statistics editor - rank counters + play time - Integral"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'statistics-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTStatisticsPanel then INTStatisticsPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>512</ID>
          <Description>"Room &amp; encounter loader - Integral"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'room-loader-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTRoomPanel then INTRoomPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>508</ID>
          <Description>"Defeat current boss - Integral (Ocelot/Tank/Ninja/Mantis/Wolf1 confirmed)"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
local result=dofile(dir..'int-boss-actions.lua').defeatCurrentBoss()
if result and result.pending then return end
local timer=createTimer(nil,false);timer.Interval=100
timer.OnTimer=function()timer.Enabled=false;timer.destroy()
 local r=getAddressList().getMemoryRecordByID(508)
 if r and r.Description:match('^Defeat current boss')and r.Active then r.Active=false end
end;timer.Enabled=true
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTNinjaDefeat and not INTNinjaDefeat.stopped then INTNinjaDefeat.stop('Disabled by user')end
if INTMantisDefeat and not INTMantisDefeat.stopped then INTMantisDefeat.stop('Disabled by user')end
-- Other boss actions are one-shot.
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>510</ID>
          <Description>"Proximity auto knockout - Integral"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'int-guard-proximity.lua').enable('knockout')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTGuardProximity then INTGuardProximity.disable('knockout')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>511</ID>
          <Description>"Proximity auto kill - Integral"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'int-guard-proximity.lua').enable('kill')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTGuardProximity then INTGuardProximity.disable('kill')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>600</ID>
          <Description>"Debugging - Integral monitors and guard actions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
-- Reveal only.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({501,507,509})do local r=getAddressList().getMemoryRecordByID(id);if r and r.Active then r.Active=false end end
{$asm}
</AssemblerScript>
          <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
          <Color>0000FF</Color>
          <CheatEntries>
            <CheatEntry>
              <ID>501</ID>
              <Description>"Dashboard / recorder (F7) - Integral read-only"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
if not INTDashboard then dofile(dir..'dashboard.lua')end
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTDashboard then assert(INTDashboard.stop())end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>509</ID>
              <Description>"Guard state - Integral knockout / kill"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'guard-state-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTGuardStatePanel then INTGuardStatePanel.stop()end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>507</ID>
              <Description>"Boss dashboard - Integral encounters (read-only)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.integral
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Integral/';local f=io.open(candidate..'int-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
INTTableDir=dir
dofile(dir..'boss-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if INTBossDashboard then INTBossDashboard.stop()end
{$asm}
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>700</ID>
      <Description>"Special Missions"</Description>
      <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Open this section without enabling gameplay features.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({714,713,712,710,711,800,704,703,702,705,701,709})do
 local row=getAddressList().getMemoryRecordByID(id)
 if row and row.Active then row.Active=false;assert(not row.Active,'Could not stop '..row.Description)end
end
{$asm}
</AssemblerScript>
      <CheatEntries>
        <CheatEntry>
          <ID>702</ID>
          <Description>"Health protection + heal - Special Missions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-toggles.lua').enable('health')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMToggles then local ok,err=SPMToggles.disable('health');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>703</ID>
          <Description>"Unlimited owned ammo + grenades - Special Missions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-toggles.lua').enable('ammo')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMToggles then local ok,err=SPMToggles.disable('ammo');assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>704</ID>
          <Description>"No alert - recognized Special Missions guards/cameras"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-no-alert.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMNoAlert then local ok,err=SPMNoAlert.disable();assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>705</ID>
          <Description>"Weapon &amp; gadget selector - Special Missions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'inventory-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMInventoryPanel then SPMInventoryPanel.stop()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>712</ID>
          <Description>"Advanced + Special access - no fake clears"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-unlocks.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMUnlocks then local ok,err=SPMUnlocks.disable();assert(ok,err)end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>714</ID>
          <Description>"Freeze mission countdown - dynamic Special Missions timer"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-timer.lua').enable()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMTimer then SPMTimer.disable()end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>713</ID>
          <Description>"Auto-clear current mission - one-shot"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
local M=dofile(dir..'spm-mission-clear.lua');M.apply()
local timer=createTimer(nil,false);timer.Interval=100
timer.OnTimer=function()timer.Enabled=false;timer.destroy();local r=getAddressList().getMemoryRecordByID(713);if r and r.Active then r.Active=false end end
timer.Enabled=true
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
-- One-shot clear cannot be undone by unchecking; no persistent controller.
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>710</ID>
          <Description>"Proximity auto knockout - Special Missions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-guard-proximity.lua').enable('knockout')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMGuardProximity then SPMGuardProximity.disable('knockout')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>711</ID>
          <Description>"Proximity auto kill - Special Missions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'spm-guard-proximity.lua').enable('kill')
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMGuardProximity then SPMGuardProximity.disable('kill')end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>800</ID>
          <Description>"Debugging - Special Missions monitor and guard actions"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
-- Reveal children only.
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
for _,id in ipairs({701,709})do local r=getAddressList().getMemoryRecordByID(id);if r and r.Active then r.Active=false end end
{$asm}
</AssemblerScript>
          <Color>0000FF</Color>
          <Options moHideChildren="1" moDeactivateChildrenAsWell="1" />
          <CheatEntries>
            <CheatEntry>
              <ID>701</ID>
              <Description>"Dashboard / recorder (F7) - Special Missions read-only"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
if not SPMDashboard then dofile(dir..'dashboard.lua')end
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMDashboard then assert(SPMDashboard.stop())end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
            <CheatEntry>
              <ID>709</ID>
              <Description>"Guard state - Special Missions knockout / kill"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
local dir=assert(MGSBundle,'Allow the embedded table Lua script').dirs.special
if not dir then local ok,path=pcall(function()return getMainForm().OpenDialog1.FileName end)
 if ok and type(path)=='string'then local parent=path:match('^(.*[\\/])')
  if parent then local candidate=parent..'Special-Missions/';local f=io.open(candidate..'spm-reader.lua','r');if f then f:close();dir=candidate end end end end
assert(dir,'Open the CT from its extracted Table folder')
SPMTableDir=dir
dofile(dir..'guard-state-panel.lua').show()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if SPMGuardStatePanel then SPMGuardStatePanel.stop()end
{$asm}
</AssemblerScript>
              <Color>0000FF</Color>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
  </CheatEntries>
  <LuaScript>-- Embedded Lua bundle. Extraction only: never enables cheats or writes game memory.
assert(type(getTempFolder)=='function','This table requires Cheat Engine Lua support')
local fs=lfs or require('lfs')
local base=getTempFolder():gsub(string.char(92),'/')
if base:sub(-1)~='/'then base=base..'/'end
local root=base..'MGS-CT-37e9633c62db3b08/'
local function mkdir(path)
 if fs.attributes(path,'mode')~='directory'then assert(fs.mkdir(path),'Cannot create bundle directory: '..path)end
end
mkdir(root)
mkdir(root..[====[Table]====])
mkdir(root..[====[Table/Integral]====])
mkdir(root..[====[Table/VR-Missions]====])
mkdir(root..[====[Table/Special-Missions]====])
mkdir(root..[====[logs]====])
local files={
 [ [====[boss-panel.lua]====] ]=([====[!-- Independent CE-side boss monitor. No dependency on gameplay cheat timers.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSBossDashboard and MGSBossDashboard.pid==getOpenedProcessID()then MGSBossDashboard.show();return MGSBossDashboard end
if MGSBossDashboard then MGSBossDashboard.stop()end
local B=dofile(dir..'mgs-boss.lua');local P={pid=B.pid,reader=B.reader,bossReader=B,stopped=false,samples=0,captured={}}
local form=createForm(false);P.form=form;form.Caption='Metal Gear Solid - Boss Dashboard (Read-only)'
form.Width=780;form.Height=650;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local title=createLabel(form);title.Left=14;title.Top=12;title.Caption='Boss observer | health-bar discovery + encounter recorder'
local note=createLabel(form);note.Left=14;note.Top=38;note.Caption='Ocelot health validated. State counters are raw updates; attack cooldowns remain unmapped.'
local auto=createCheckBox(form);auto.Left=14;auto.Top=65;auto.Caption='Auto-capture each new boss (local diagnostic files, up to 8)';auto.Checked=true
local button=createButton(form);P.captureButton=button;button.Left=14;button.Top=96;button.Width=225;button.Height=30;button.Caption='Capture current boss data'
local memo=createMemo(form);P.memo=memo;memo.Left=14;memo.Top=139;memo.Width=748;memo.Height=480
memo.ReadOnly=true;memo.WordWrap=false;memo.ScrollBars='ssBoth';memo.Font.Name='Consolas';memo.Font.Size=10
local csv,logSize,lastRow
local path=dir..'../logs/boss-observer-'..B.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'-'..getTickCount()..'.csv';P.logPath=path
local ok,err=pcall(function()csv=assert(io.open(path,'w'));assert(csv:write('utc,area,boss,actor,health_bar,max_bar,hp,max_hp,phase,state_counter,rounds,attack_timer,evidence\n'));logSize=csv:seek()end)
if not ok then P.logError=tostring(err)end
local function capture(c,b)
 local ok,result=pcall(B.capture,c,b);if ok then P.captureStatus=result else P.captureStatus='Capture stopped: '..tostring(result)end
end
local function csvRow(values)
 local out={};for i,v in ipairs(values)do out[i]='"'..tostring(v):gsub('"','""')..'"'end
 return table.concat(out,',')
end
button.OnClick=function()if P.state and P.state.bosses[1]then capture(P.state,P.state.bosses[1]);P.tick()end end
function P.tick()
 if P.stopped then return end;P.samples=P.samples+1
 local ok,c=pcall(B.inspect);P.state=ok and c or nil;button.Enabled=ok and #c.bosses&gt;0 or false
 if not ok then memo.Lines.Text='READ ONLY | Waiting for valid gameplay\r\nPrevious boss readings cleared.\r\n'..tostring(c);return end
 local text={'READ ONLY | Steam build 20872173 | US base game',
  'Area: '..c.stage..' | Snake HP: '..c.playerHealth..' | PID: '..P.pid,'',
  #c.bosses==0 and 'No supported boss actor is loaded.'or 'Boss detected.'}
 local rows={}
 for _,b in ipairs(c.bosses)do
  local a=b.actor;local identity=string.format('%s:%X:%X',c.stage,a.offset,a.act)
  if auto.Checked and not P.captured[identity]then P.captured[identity]=true;capture(c,b)end
  text[#text+1]='';text[#text+1]=b.name
  text[#text+1]=b.bar and string.format('Health bar: %d / %d (%.1f%%)',b.bar,b.maximum,b.percent)or 'Health bar: unresolved'
  if b.hp then text[#text+1]=string.format('Actual HP: %d / %d',b.hp,b.maxHP)end
  text[#text+1]='Phase: '..b.phase..' | Attack timer: '..b.attackTimer
  if b.stateCounter then text[#text+1]='State counter: '..b.stateCounter..' (raw updates, not seconds)'end
  if b.rounds then text[#text+1]='Ocelot cylinder: '..b.rounds..' / '..b.cylinder end
  text[#text+1]='Evidence: '..b.evidence
  if b.binding then text[#text+1]=string.format('Native field: +%X, scale %d; call %08X',b.binding.offset,b.binding.scale,b.binding.callPC)end
  if b.reason then text[#text+1]=b.reason end
  text[#text+1]=string.format('Position candidate: %d, %d, %d (unvalidated)',table.unpack(b.positionCandidate))
  text[#text+1]=string.format('Actor: %08X | %s | level %d',0x80000000+a.offset,a.name,a.level)
  rows[#rows+1]=csvRow({c.stage,b.name,string.format('%08X',0x80000000+a.offset),b.bar or '',b.maximum or '',b.hp or '',b.maxHP or '',b.phase,b.stateCounter or '',b.rounds or '',b.attackTimer,b.evidence})
 end
 if #rows==0 then rows[1]=csvRow({c.stage,'None','','','','','','','','','','No boss loaded'})end
 local row=table.concat(rows,'\n')
 if csv and row~=lastRow then
  local written,why=pcall(function()
   for _,v in ipairs(rows)do assert(csv:write(os.date('!%Y-%m-%dT%H:%M:%SZ')..','..v..'\n'))end
   csv:flush();logSize=csv:seek();assert(logSize&lt;10*1024*1024,'10 MiB log limit reached')
  end)
  if not written then P.logError=tostring(why);pcall(function()csv:close()end);csv=nil end
  lastRow=row
 end
 text[#text+1]='';text[#text+1]='Loaded overlay actors:'
 for i,a in ipairs(c.actors)do if i&lt;=45 then text[#text+1]=string.format('  %-24s %08X',a.name or '?',0x80000000+a.offset)end end
 text[#text+1]='';text[#text+1]='No target memory writes, hooks, spawns, teleports or save actions.'
 text[#text+1]='Sample: 250 ms | Captures: '..B.captures..'/8 | Close to stop'
 if P.captureStatus then text[#text+1]='Capture: '..P.captureStatus end
 if P.logError then text[#text+1]='Log: '..P.logError end
 memo.Lines.Text=table.concat(text,'\r\n')
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 if csv then csv:close();csv=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if MGSBossDashboard==P then MGSBossDashboard=nil end
 local e=getAddressList().getMemoryRecordByID(7)
 if e and e.Description:match('^Boss dashboard')and e.Active then e.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=250;timer.OnTimer=P.tick
MGSBossDashboard=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[dashboard.lua]====] ]=([====[!-- CE-side window and change log. All game access is through read-only reads.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSDashboard then
 MGSDashboard.stop()
 assert(not MGSDashboard,'Close the previous dashboard before reloading')
end
local R=dofile(dir..'mgs-reader.lua')
local D={reader=R,pid=R.pid,samples=0,changes=0,errors=0,label='baseline',stopped=false}
local logPath=dir..'../logs/state-'..R.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'.csv'
local csv=assert(io.open(logPath,'w'));D.logPath=logPath
local columns={'utc','label','health','max_health','weapon_id','item_id','total_ammo','ammo_capacity','magazine','mag_capacity','alert_mode','alert_level','ration','ration_capacity'}
for i=1,10 do columns[#columns+1]='ammo_'..(i-1)end
csv:write(table.concat(columns,',')..'\n');csv:flush()
local form=createForm(false);D.form=form;form.Caption='Metal Gear Solid - Monitor';form.Width=660;form.Height=700
form.Position='poScreenCenter'
local memo=createMemo(form);D.memo=memo;memo.Align='alClient';memo.ReadOnly=true;memo.ScrollBars='ssVertical';memo.WordWrap=false
memo.Font.Name='Consolas';memo.Font.Size=11
local function value(v)return v==nil and '--'or tostring(v)end
local function csvValue(v)return '"'..tostring(v or ''):gsub('"','""')..'"'end
function D.mark(label)
 assert(type(label)=='string'and #label&lt;=80,'Short test label required')
 D.label=label;D.last=nil
end
local function display(h)
 local rows={'READ-ONLY MONITOR | Steam build 20872173 | US base game',
  'Health, SOCOM ammo and alert/evasion observed in live play','',
  string.format('Health       %d / %d (%.1f%%)',h.health,h.maximum,100*h.health/h.maximum),
  'Weapon       '..h.weaponName,
  'Total ammo   '..value(h.ammoSelected)..' / '..value(h.ammoSelectedMax),
  'Magazine     '..((h.weapon==0 or h.weapon==1)and (h.magazine..' / '..h.magazineMax)or 'N/A')}
 -- The inventory count includes rounds in the magazine; it is not spare ammo.
 rows[#rows+1]='Rations      '..h.ration..' / '..h.rationMax
 rows[#rows+1]='';rows[#rows+1]='Alert mode   '..h.alertName..' ('..h.alertMode..')'
 rows[#rows+1]='Alert level  '..h.alertLevel..' (raw; not assumed seconds/percent)'
 rows[#rows+1]='';rows[#rows+1]='Inventory ammo (total / capacity)'
 for i,name in ipairs(R.weapons)do
  rows[#rows+1]=string.format('  %-15s %s',name,h.ammo[i]&lt;0 and 'Not owned'or (h.ammo[i]..' / '..h.ammoMax[i]))
 end
 rows[#rows+1]='';rows[#rows+1]='Sample every 100 ms | F7 hide/show | Close to stop'
 rows[#rows+1]='Monitor reads only. Optional cheats are separate CT entries.'
 if MGSToggles then
  rows[#rows+1]='Health protection: '..MGSToggles.health.status
  rows[#rows+1]='Unlimited ammo: '..MGSToggles.ammo.status
 end
 if MGSNoAlert then rows[#rows+1]='No alert: '..MGSNoAlert.status end
 rows[#rows+1]='Test: '..D.label..' | samples '..D.samples..' | changes '..D.changes
 if D.logError then rows[#rows+1]='Logging stopped: '..D.logError end
 memo.Lines.Text=table.concat(rows,'\r\n')
end
function D.tick()
 if D.stopped then return end
 local ok,h=pcall(R.read)
 if not ok then
  D.state=nil;D.errors=D.errors+1;D.error=tostring(h)
  memo.Lines.Text='READ ONLY | Waiting for valid gameplay\r\n'..D.error..'\r\nPrevious values cleared.'
  return
 end
 D.state=h;D.error=nil;D.samples=D.samples+1
 local fields={D.label,h.health,h.maximum,h.weapon,h.item,value(h.ammoSelected),value(h.ammoSelectedMax),h.magazine,h.magazineMax,h.alertMode,h.alertLevel,h.ration,h.rationMax}
 for i=1,10 do fields[#fields+1]=h.ammo[i]end
 local row={};for _,v in ipairs(fields)do row[#row+1]=csvValue(v)end;row=table.concat(row,',')
 if row~=D.last then
  D.changes=D.changes+1;D.last=row
  if csv then
   local logged,err=pcall(function()
    assert(csv:write(os.date('!%Y-%m-%dT%H:%M:%SZ')..','..row..'\n'));assert(csv:flush())
    if csv:seek()&gt;10*1024*1024 then csv:close();csv=nil;D.logError='10 MiB log limit reached'end
   end)
   if not logged then D.logError=tostring(err);pcall(function()csv:close()end);csv=nil end
  end
 end
 display(h)
end
function D.stop(closing)
 if D.stopped then return true end
 D.stopped=true
 if D.timer then D.timer.Enabled=false;D.timer.destroy();D.timer=nil end
 if D.hotkey then D.hotkey.destroy();D.hotkey=nil end
 if csv then csv:close();csv=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if MGSDashboard==D then MGSDashboard=nil end
 -- Closing the diagnostic window affects only its own CT entry.
 local r=getAddressList().getMemoryRecordByID(1)
 if r and r.Description:match('^Dashboard')and r.Active then r.Active=false end
 return true
end
form.OnClose=function()local ok=D.stop(true);return ok and caFree or caNone end
D.hotkey=createHotkey(function()form.Visible=not form.Visible end,0x76)
local timer=createTimer(form,false);D.timer=timer;timer.Interval=100;timer.OnTimer=D.tick
MGSDashboard=D;D.tick();timer.Enabled=true;form.show()
return D
]====]):sub(2),
 [ [====[guard-state-panel.lua]====] ]=([====[!local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSGuardStatePanel and MGSGuardStatePanel.pid==getOpenedProcessID()then MGSGuardStatePanel.show();return MGSGuardStatePanel end
if MGSGuardStatePanel then MGSGuardStatePanel.stop()end
local A=dofile(dir..'mgs-guard-state.lua')
local C=dofile(dir..'mgs-guard-proximity.lua')
local P={pid=A.pid,actions=A,stopped=false}
local f=createForm(false);P.form=f;f.Caption='Metal Gear Solid - Guard state'
f.Width=760;f.Height=655;f.Position='poScreenCenter';f.Font.Name='Segoe UI';f.Font.Size=10
local function label(y,s)
 local v=createLabel(f);v.Left=16;v.Top=y;v.AutoSize=false;v.Width=720;v.Height=40;v.WordWrap=true;v.Caption=s;return v
end
label(12,'One-shot actions for standard guards loaded in the current area.')
label(48,'Knockout preserves health. Extended knockout delays recovery. Kill follows normal death logic and can increase the kill count.')
label(94,'Busy, already down, and unsupported guards are skipped. Cameras, bosses, civilians and Snake are excluded.')
local info=label(138,'');info.Height=48
local memo=createMemo(f);memo.Left=16;memo.Top=266;memo.Width=720;memo.Height=160;memo.ReadOnly=true;memo.ScrollBars='ssVertical'
local status=label(435,'');status.Height=60
local extended=createCheckBox(f);extended.Left=16;extended.Top=190;extended.Caption='Extended knockout (~60 seconds)';extended.Checked=true
local dl=createLabel(f);dl.Left=332;dl.Top=194;dl.Caption='Delay (seconds):'
local delay=createEdit(f);delay.Left=459;delay.Top=189;delay.Width=46;delay.Text='5'
local cancel=createButton(f);cancel.Left=535;cancel.Top=186;cancel.Width=201;cancel.Height=28;cancel.Caption='Cancel scheduled action';cancel.Enabled=false
local buttons={}
local function button(x,width,text,fn)
 local b=createButton(f);b.Left=x;b.Top=225;b.Width=width;b.Height=30;b.Caption=text;b.OnClick=fn;return b
end
function P.refresh()
 if P.stopped then return end
 local ok,c=pcall(A.inspect);P.state=ok and c or nil
 buttons[1].Enabled=ok and c.eligible&gt;0 and not P.pending or false;buttons[2].Enabled=buttons[1].Enabled
 local lines={}
 if ok then
  info.Caption=string.format('Area: %s | Loaded: %d | Ready: %d | Knocked out: %d | Dead: %d | Busy: %d',c.stage,c.total,c.eligible,c.knockedOut,c.dead,c.skipped)
  for _,g in ipairs(c.guards)do lines[#lines+1]=string.format('Guard %d | HP %d | stun %d | %s',g.actor.slot,g.hp,g.faint,g.eligible and 'Ready'or g.reason)end
  if c.reason then lines[#lines+1]=c.reason end
 else info.Caption='Waiting for supported gameplay.';lines[1]=tostring(c)end
 memo.Lines.Text=table.concat(lines,'\r\n');status.Caption=P.error or A.status
 if A.logError then status.Caption=status.Caption..' Log: '..A.logError end
end
local function cancelPending()
 if P.pending then P.pending.Enabled=false;P.pending.destroy();P.pending=nil end;cancel.Enabled=false
end
cancel.OnClick=function()cancelPending();P.error=nil;A.status='Scheduled action cancelled.';P.refresh()end
local function action(mode)
 P.error=nil
 local ok,err=pcall(function()
  local seconds=tonumber(delay.Text)
  assert(seconds and seconds==math.floor(seconds)and seconds&gt;=0 and seconds&lt;=15,'Delay must be 0..15 seconds.')
  local armed=A.inspect();local long=extended.Checked
  local function execute()
   cancelPending()
   local success,result=pcall(function()
    local c=A.inspect();assert(c.ram==armed.ram and c.stage==armed.stage,'Area changed; scheduled action cancelled.')
    local outcome=A.apply(mode)
    if mode=='knockout'and long then A.extendKnockout(outcome,1800)end
    return outcome
   end)
   P.error=not success and tostring(result)or nil;P.refresh()
  end
  cancelPending()
  if seconds==0 then execute();return end
  local timer=createTimer(nil,false);P.pending=timer;timer.Interval=1000;cancel.Enabled=true
  A.status=mode..' in '..seconds..' seconds. Switch back to the game.'
  timer.OnTimer=function()
   seconds=seconds-1
   if seconds&lt;=0 then execute()else status.Caption=mode..' in '..seconds..' seconds. Switch back to the game.'end
  end
  timer.Enabled=true
 end)
 P.error=not ok and tostring(err)or P.error;P.refresh()
end
buttons[1]=button(16,245,'Knock out loaded guards',function()action('knockout')end)
buttons[2]=button(275,245,'Kill loaded guards',function()action('kill')end)
button(535,201,'Refresh (read-only)',function()P.error=nil;P.refresh()end)
label(502,'Proximity: enable row 10 for knockout or row 11 for kill. Only one mode runs at a time.')
local rl=createLabel(f);rl.Left=16;rl.Top=550;rl.Caption='Radius (game units):'
local radius=createEdit(f);radius.Left=178;radius.Top=545;radius.Width=80;radius.Text=tostring(C.radius)
local applyRadius=createButton(f);applyRadius.Left=275;applyRadius.Top=543;applyRadius.Width=150;applyRadius.Height=28;applyRadius.Caption='Apply radius'
local stopAuto=createButton(f);stopAuto.Left=445;stopAuto.Top=543;stopAuto.Width=165;stopAuto.Height=28;stopAuto.Caption='Stop proximity'
local autoStatus=label(583,'');autoStatus.Height=54
applyRadius.OnClick=function()
 local ok,err=pcall(C.setRadius,radius.Text);P.error=not ok and tostring(err)or nil;P.refresh()
end
stopAuto.OnClick=function()C.disable();P.error=nil;P.refresh()end
local statusTimer=createTimer(f,false);P.statusTimer=statusTimer;statusTimer.Interval=500
statusTimer.OnTimer=function()autoStatus.Caption=C.status end;statusTimer.Enabled=true;autoStatus.Caption=C.status
function P.show()f.show()end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 cancelPending();if A.extension then A.extension.stop()end
 if P.statusTimer then P.statusTimer.Enabled=false;P.statusTimer.destroy();P.statusTimer=nil end
 if not closing then f.OnClose=nil;f.destroy()end
 if MGSGuardStatePanel==P then MGSGuardStatePanel=nil end
 local row=getAddressList().getMemoryRecordByID(9)
 if row and row.Description:match('^Guard state')and row.Active then row.Active=false end
 return true
end
f.OnClose=function()P.stop(true);return caFree end
MGSGuardStatePanel=P;P.refresh();P.show();return P
]====]):sub(2),
 [ [====[Integral/boss-panel.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Independent CE-side boss monitor. No dependency on gameplay cheat timers.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTBossDashboard and INTBossDashboard.pid==getOpenedProcessID()then INTBossDashboard.show();return INTBossDashboard end
if INTBossDashboard then INTBossDashboard.stop()end
local B=dofile(dir..'int-boss-observer.lua');local P={pid=B.pid,reader=B.reader,bossReader=B,stopped=false,samples=0,captured={}}
local form=createForm(false);P.form=form;form.Caption='Integral - Boss Dashboard (Read-only)'
form.Width=780;form.Height=650;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local title=createLabel(form);title.Left=14;title.Top=12;title.Caption='Boss observer | health-bar discovery + encounter recorder'
local note=createLabel(form);note.Left=14;note.Top=38;note.Caption='Ocelot/Tank/Ninja/Mantis/Wolf1 defeat confirmed. Other encounters need testing.'
local auto=createCheckBox(form);auto.Left=14;auto.Top=65;auto.Caption='Auto-capture each new boss (local diagnostic files, up to 8)';auto.Checked=true
local button=createButton(form);P.captureButton=button;button.Left=14;button.Top=96;button.Width=225;button.Height=30;button.Caption='Capture current boss data'
local memo=createMemo(form);P.memo=memo;memo.Left=14;memo.Top=139;memo.Width=748;memo.Height=480
memo.ReadOnly=true;memo.WordWrap=false;memo.ScrollBars='ssBoth';memo.Font.Name='Consolas';memo.Font.Size=10
local csv,logSize,lastRow
local path=dir..'../../logs/integral-boss-observer-'..B.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'-'..getTickCount()..'.csv';P.logPath=path
local ok,err=pcall(function()csv=assert(io.open(path,'w'));assert(csv:write('utc,area,boss,actor,health_bar,max_bar,hp,max_hp,phase,state_counter,rounds,attack_timer,evidence\n'));logSize=csv:seek()end)
if not ok then P.logError=tostring(err)end
local function capture(c,b)
 local ok,result=pcall(B.capture,c,b);if ok then P.captureStatus=result else P.captureStatus='Capture stopped: '..tostring(result)end
end
local function csvRow(values)
 local out={};for i,v in ipairs(values)do out[i]='"'..tostring(v):gsub('"','""')..'"'end
 return table.concat(out,',')
end
button.OnClick=function()if P.state and P.state.bosses[1]then capture(P.state,P.state.bosses[1]);P.tick()end end
function P.tick()
 if P.stopped then return end;P.samples=P.samples+1
 local ok,c=pcall(B.inspect);P.state=ok and c or nil;button.Enabled=ok and #c.bosses&gt;0 or false
 if not ok then memo.Lines.Text='READ ONLY | Waiting for valid gameplay\r\nPrevious boss readings cleared.\r\n'..tostring(c);return end
 local text={'READ ONLY | Steam build 20872173 | Integral JP',
  'Area: '..c.stage..' | Snake HP: '..c.playerHealth..' | PID: '..P.pid,'',
  #c.bosses==0 and 'No supported boss actor is loaded.'or 'Boss detected.'}
 local rows={}
 for _,b in ipairs(c.bosses)do
  local a=b.actor;local identity=string.format('%s:%X:%X',c.stage,a.offset,a.act)
  if auto.Checked and not P.captured[identity]then P.captured[identity]=true;capture(c,b)end
  text[#text+1]='';text[#text+1]=b.name
  text[#text+1]=b.bar and string.format('Health bar: %d / %d (%.1f%%)',b.bar,b.maximum,b.percent)or 'Health bar: unresolved'
  if b.hp then text[#text+1]=string.format('Actual HP: %d / %d',b.hp,b.maxHP)end
  text[#text+1]='Phase: '..b.phase..' | Attack timer: '..b.attackTimer
  if b.stateCounter then text[#text+1]='State counter: '..b.stateCounter..' (raw updates, not seconds)'end
  if b.rounds then text[#text+1]='Ocelot cylinder: '..b.rounds..' / '..b.cylinder end
  text[#text+1]='Evidence: '..b.evidence
  if b.binding then text[#text+1]=string.format('Native field: +%X, scale %d; call %08X',b.binding.offset,b.binding.scale,b.binding.callPC)end
  if b.reason then text[#text+1]=b.reason end
  text[#text+1]=string.format('Position candidate: %d, %d, %d (unvalidated)',table.unpack(b.positionCandidate))
  text[#text+1]=string.format('Actor: %08X | %s | level %d',0x80000000+a.offset,a.name,a.level)
  rows[#rows+1]=csvRow({c.stage,b.name,string.format('%08X',0x80000000+a.offset),b.bar or '',b.maximum or '',b.hp or '',b.maxHP or '',b.phase,b.stateCounter or '',b.rounds or '',b.attackTimer,b.evidence})
 end
 if #rows==0 then rows[1]=csvRow({c.stage,'None','','','','','','','','','','No boss loaded'})end
 local row=table.concat(rows,'\n')
 if csv and row~=lastRow then
  local written,why=pcall(function()
   for _,v in ipairs(rows)do assert(csv:write(os.date('!%Y-%m-%dT%H:%M:%SZ')..','..v..'\n'))end
   csv:flush();logSize=csv:seek();assert(logSize&lt;10*1024*1024,'10 MiB log limit reached')
  end)
  if not written then P.logError=tostring(why);pcall(function()csv:close()end);csv=nil end
  lastRow=row
 end
 text[#text+1]='';text[#text+1]='Loaded overlay actors:'
 for i,a in ipairs(c.actors)do if i&lt;=45 then text[#text+1]=string.format('  %-24s %08X',a.name or '?',0x80000000+a.offset)end end
 text[#text+1]='';text[#text+1]='No target memory writes, hooks, spawns, teleports or save actions.'
 text[#text+1]='Sample: 250 ms | Captures: '..B.captures..'/8 | Close to stop'
 if P.captureStatus then text[#text+1]='Capture: '..P.captureStatus end
 if P.logError then text[#text+1]='Log: '..P.logError end
 memo.Lines.Text=table.concat(text,'\r\n')
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 if csv then csv:close();csv=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if INTBossDashboard==P then INTBossDashboard=nil end
 local e=getAddressList().getMemoryRecordByID(507)
 if e and e.Description:match('^Boss dashboard')and e.Active then e.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=250;timer.OnTimer=P.tick
INTBossDashboard=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[Integral/dashboard.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- CE-side window and change log. All game access is through read-only reads.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTDashboard then
 INTDashboard.stop()
 assert(not INTDashboard,'Close the previous dashboard before reloading')
end
local R=dofile(dir..'int-reader.lua')
local D={reader=R,pid=R.pid,samples=0,changes=0,errors=0,label='baseline',stopped=false}
local logPath=dir..'../../logs/integral-state-'..R.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'.csv'
local csv=assert(io.open(logPath,'w'));D.logPath=logPath
local columns={'utc','label','health','max_health','weapon_id','item_id','total_ammo','ammo_capacity','magazine','mag_capacity','alert_mode','alert_level','ration','ration_capacity'}
for i=1,10 do columns[#columns+1]='ammo_'..(i-1)end
csv:write(table.concat(columns,',')..'\n');csv:flush()
local form=createForm(false);D.form=form;form.Caption='Integral - Monitor';form.Width=660;form.Height=700
form.Position='poScreenCenter'
local memo=createMemo(form);D.memo=memo;memo.Align='alClient';memo.ReadOnly=true;memo.ScrollBars='ssVertical';memo.WordWrap=false
memo.Font.Name='Consolas';memo.Font.Size=11
local function value(v)return v==nil and '--'or tostring(v)end
local function csvValue(v)return '"'..tostring(v or ''):gsub('"','""')..'"'end
function D.mark(label)
 assert(type(label)=='string'and #label&lt;=80,'Short test label required')
 D.label=label;D.last=nil
end
local function display(h)
 local rows={'READ-ONLY MONITOR | Steam build 20872173 | Integral',
  'Integral port: native mapping checked; live feature tests pending','',
  string.format('Health       %d / %d (%.1f%%)',h.health,h.maximum,100*h.health/h.maximum),
  'Weapon       '..h.weaponName,
  'Total ammo   '..value(h.ammoSelected)..' / '..value(h.ammoSelectedMax),
  'Magazine     '..((h.weapon==0 or h.weapon==1)and (h.magazine..' / '..h.magazineMax)or 'N/A')}
 -- The inventory count includes rounds in the magazine; it is not spare ammo.
 rows[#rows+1]='Rations      '..h.ration..' / '..h.rationMax
 rows[#rows+1]='';rows[#rows+1]='Alert mode   '..h.alertName..' ('..h.alertMode..')'
 rows[#rows+1]='Alert level  '..h.alertLevel..' (raw; not assumed seconds/percent)'
 rows[#rows+1]='';rows[#rows+1]='Inventory ammo (total / capacity)'
 for i,name in ipairs(R.weapons)do
  rows[#rows+1]=string.format('  %-15s %s',name,h.ammo[i]&lt;0 and 'Not owned'or (h.ammo[i]..' / '..h.ammoMax[i]))
 end
 rows[#rows+1]='';rows[#rows+1]='Sample every 100 ms | F7 hide/show | Close to stop'
 rows[#rows+1]='Monitor reads only. Optional cheats are separate CT entries.'
 if INTToggles then
  rows[#rows+1]='Health protection: '..INTToggles.health.status
  rows[#rows+1]='Unlimited ammo: '..INTToggles.ammo.status
 end
 if INTNoAlert then rows[#rows+1]='No alert: '..INTNoAlert.status end
 rows[#rows+1]='Test: '..D.label..' | samples '..D.samples..' | changes '..D.changes
 if D.logError then rows[#rows+1]='Logging stopped: '..D.logError end
 memo.Lines.Text=table.concat(rows,'\r\n')
end
function D.tick()
 if D.stopped then return end
 local ok,h=pcall(R.read)
 if not ok then
  D.state=nil;D.errors=D.errors+1;D.error=tostring(h)
  memo.Lines.Text='READ ONLY | Waiting for valid gameplay\r\n'..D.error..'\r\nPrevious values cleared.'
  return
 end
 D.state=h;D.error=nil;D.samples=D.samples+1
 local fields={D.label,h.health,h.maximum,h.weapon,h.item,value(h.ammoSelected),value(h.ammoSelectedMax),h.magazine,h.magazineMax,h.alertMode,h.alertLevel,h.ration,h.rationMax}
 for i=1,10 do fields[#fields+1]=h.ammo[i]end
 local row={};for _,v in ipairs(fields)do row[#row+1]=csvValue(v)end;row=table.concat(row,',')
 if row~=D.last then
  D.changes=D.changes+1;D.last=row
  if csv then
   local logged,err=pcall(function()
    assert(csv:write(os.date('!%Y-%m-%dT%H:%M:%SZ')..','..row..'\n'));assert(csv:flush())
    if csv:seek()&gt;10*1024*1024 then csv:close();csv=nil;D.logError='10 MiB log limit reached'end
   end)
   if not logged then D.logError=tostring(err);pcall(function()csv:close()end);csv=nil end
  end
 end
 display(h)
end
function D.stop(closing)
 if D.stopped then return true end
 D.stopped=true
 if D.timer then D.timer.Enabled=false;D.timer.destroy();D.timer=nil end
 if D.hotkey then D.hotkey.destroy();D.hotkey=nil end
 if csv then csv:close();csv=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if INTDashboard==D then INTDashboard=nil end
 -- Closing the diagnostic window affects only its own CT entry.
 local r=getAddressList().getMemoryRecordByID(501)
 if r and r.Description:match('^Dashboard')and r.Active then r.Active=false end
 return true
end
form.OnClose=function()local ok=D.stop(true);return ok and caFree or caNone end
D.hotkey=createHotkey(function()form.Visible=not form.Visible end,0x76)
local timer=createTimer(form,false);D.timer=timer;timer.Interval=100;timer.OnTimer=D.tick
INTDashboard=D;D.tick();timer.Enabled=true;form.show()
return D
]====]):sub(2),
 [ [====[Integral/guard-state-panel.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTGuardStatePanel and INTGuardStatePanel.pid==getOpenedProcessID()then INTGuardStatePanel.show();return INTGuardStatePanel end
if INTGuardStatePanel then INTGuardStatePanel.stop()end
local A=dofile(dir..'int-guard-state.lua')
local C=dofile(dir..'int-guard-proximity.lua')
local P={pid=A.pid,actions=A,stopped=false}
local f=createForm(false);P.form=f;f.Caption='Integral - Guard state'
f.Width=760;f.Height=655;f.Position='poScreenCenter';f.Font.Name='Segoe UI';f.Font.Size=10
local function label(y,s)
 local v=createLabel(f);v.Left=16;v.Top=y;v.AutoSize=false;v.Width=720;v.Height=40;v.WordWrap=true;v.Caption=s;return v
end
label(12,'One-shot actions for standard guards loaded in the current area.')
label(48,'Knockout preserves health. Extended knockout delays recovery. Kill follows normal death logic and can increase the kill count.')
label(94,'Busy, already down, and unsupported guards are skipped. Cameras, bosses, civilians and Snake are excluded.')
local info=label(138,'');info.Height=48
local memo=createMemo(f);memo.Left=16;memo.Top=266;memo.Width=720;memo.Height=160;memo.ReadOnly=true;memo.ScrollBars='ssVertical'
local status=label(435,'');status.Height=60
local extended=createCheckBox(f);extended.Left=16;extended.Top=190;extended.Caption='Extended knockout (~60 seconds)';extended.Checked=true
local dl=createLabel(f);dl.Left=332;dl.Top=194;dl.Caption='Delay (seconds):'
local delay=createEdit(f);delay.Left=459;delay.Top=189;delay.Width=46;delay.Text='5'
local cancel=createButton(f);cancel.Left=535;cancel.Top=186;cancel.Width=201;cancel.Height=28;cancel.Caption='Cancel scheduled action';cancel.Enabled=false
local buttons={}
local function button(x,width,text,fn)
 local b=createButton(f);b.Left=x;b.Top=225;b.Width=width;b.Height=30;b.Caption=text;b.OnClick=fn;return b
end
function P.refresh()
 if P.stopped then return end
 local ok,c=pcall(A.inspect);P.state=ok and c or nil
 buttons[1].Enabled=ok and c.eligible&gt;0 and not P.pending or false;buttons[2].Enabled=buttons[1].Enabled
 local lines={}
 if ok then
  info.Caption=string.format('Area: %s | Loaded: %d | Ready: %d | Knocked out: %d | Dead: %d | Busy: %d',c.stage,c.total,c.eligible,c.knockedOut,c.dead,c.skipped)
  for _,g in ipairs(c.guards)do lines[#lines+1]=string.format('Guard %d | HP %d | stun %d | %s',g.actor.slot,g.hp,g.faint,g.eligible and 'Ready'or g.reason)end
  if c.reason then lines[#lines+1]=c.reason end
 else info.Caption='Waiting for supported gameplay.';lines[1]=tostring(c)end
 memo.Lines.Text=table.concat(lines,'\r\n');status.Caption=P.error or A.status
 if A.logError then status.Caption=status.Caption..' Log: '..A.logError end
end
local function cancelPending()
 if P.pending then P.pending.Enabled=false;P.pending.destroy();P.pending=nil end;cancel.Enabled=false
end
cancel.OnClick=function()cancelPending();P.error=nil;A.status='Scheduled action cancelled.';P.refresh()end
local function action(mode)
 P.error=nil
 local ok,err=pcall(function()
  local seconds=tonumber(delay.Text)
  assert(seconds and seconds==math.floor(seconds)and seconds&gt;=0 and seconds&lt;=15,'Delay must be 0..15 seconds.')
  local armed=A.inspect();local long=extended.Checked
  local function execute()
   cancelPending()
   local success,result=pcall(function()
    local c=A.inspect();assert(c.ram==armed.ram and c.stage==armed.stage,'Area changed; scheduled action cancelled.')
    local outcome=A.apply(mode)
    if mode=='knockout'and long then A.extendKnockout(outcome,1800)end
    return outcome
   end)
   P.error=not success and tostring(result)or nil;P.refresh()
  end
  cancelPending()
  if seconds==0 then execute();return end
  local timer=createTimer(nil,false);P.pending=timer;timer.Interval=1000;cancel.Enabled=true
  A.status=mode..' in '..seconds..' seconds. Switch back to the game.'
  timer.OnTimer=function()
   seconds=seconds-1
   if seconds&lt;=0 then execute()else status.Caption=mode..' in '..seconds..' seconds. Switch back to the game.'end
  end
  timer.Enabled=true
 end)
 P.error=not ok and tostring(err)or P.error;P.refresh()
end
buttons[1]=button(16,245,'Knock out loaded guards',function()action('knockout')end)
buttons[2]=button(275,245,'Kill loaded guards',function()action('kill')end)
button(535,201,'Refresh (read-only)',function()P.error=nil;P.refresh()end)
label(502,'Proximity: enable the Integral knockout or kill checkbox. Only one mode runs at a time.')
local rl=createLabel(f);rl.Left=16;rl.Top=550;rl.Caption='Radius (game units):'
local radius=createEdit(f);radius.Left=178;radius.Top=545;radius.Width=80;radius.Text=tostring(C.radius)
local applyRadius=createButton(f);applyRadius.Left=275;applyRadius.Top=543;applyRadius.Width=150;applyRadius.Height=28;applyRadius.Caption='Apply radius'
local stopAuto=createButton(f);stopAuto.Left=445;stopAuto.Top=543;stopAuto.Width=165;stopAuto.Height=28;stopAuto.Caption='Stop proximity'
local autoStatus=label(583,'');autoStatus.Height=54
applyRadius.OnClick=function()
 local ok,err=pcall(C.setRadius,radius.Text);P.error=not ok and tostring(err)or nil;P.refresh()
end
stopAuto.OnClick=function()C.disable();P.error=nil;P.refresh()end
local statusTimer=createTimer(f,false);P.statusTimer=statusTimer;statusTimer.Interval=500
statusTimer.OnTimer=function()autoStatus.Caption=C.status end;statusTimer.Enabled=true;autoStatus.Caption=C.status
function P.show()f.show()end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 cancelPending();if A.extension then A.extension.stop()end
 if P.statusTimer then P.statusTimer.Enabled=false;P.statusTimer.destroy();P.statusTimer=nil end
 if not closing then f.OnClose=nil;f.destroy()end
 if INTGuardStatePanel==P then INTGuardStatePanel=nil end
 local row=getAddressList().getMemoryRecordByID(509)
 if row and row.Description:match('^Guard state')and row.Active then row.Active=false end
 return true
end
f.OnClose=function()P.stop(true);return caFree end
INTGuardStatePanel=P;P.refresh();P.show();return P
]====]):sub(2),
 [ [====[Integral/int-boss-actions.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Optional one-shot boss cheats. The boss observer itself remains read-only.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local A={version=2}
local function u16(a)return assert(readSmallInteger(a),'Target read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Target read unavailable')&amp;0xffffffff end
function A.defeatOcelot()
 local result=dofile(dir..'int-boss.lua').defeat()
 A.last=result;INTBossActions=A;return result
end
-- This context deliberately does not require the normal Snake actor: the
-- rooftop Liquid fight uses a different player actor. The reader still checks
-- the installed executable, emulated RAM, region and resident fingerprints.
local function ready(B,c)
 assert(getOpenedProcessID()==B.pid,'Attached process changed.')
 local h=B.reader.read();local r=c.ram
 assert(h.ram==r and h.health&gt;0,'Player or RAM changed.')
 assert(u32(r+0xab3d0)==0 and u32(r+0xaba38)~=0 and u32(r+0xab3d4)==0,'Wait for normal gameplay.')
 assert(u32(r+0xab3cc)&amp;0xd40c0000==0 and u32(r+0xaba50)&amp;0x20002084==0,'Finish the scene or restricted action first.')
 assert(readString(r+0xb4d88,16)==c.stage,'Area changed.')
 -- No codec, inventory or save-slot menu. Do not invoke any menu operation.
 assert(u32(r+0xbd360+8)==0x800386a4 and u32(r+0xbd360+12)==0x800387e8,'Resident menu actor differs.')
 assert(u16(r+0xbd360+0x2a)==0,'Close the menu before using boss defeat.')
end
local function sameActor(r,a)
 assert(a.offset&gt;=0x10000 and a.offset+0x4020&lt;=0x200000,'Boss allocation window unavailable.')
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Boss actor changed.')
 local name=u32(r+a.offset+20)
 assert(name&gt;=0x80000000 and name&lt;0x80200000 and readString(r+(name&amp;0x1fffff),48)==a.name,'Boss identity changed.')
end
function A.defeatCurrentBoss(nativeOnly)
 local B=dofile(dir..'int-boss-observer.lua');local c=B.inspect()
 if not nativeOnly and c.stage=='s07b'and #c.bosses==0 then
  for _,a in ipairs(c.actors)do if a.name=='meryl07b.c'then
   return dofile(dir..'int-boss-mantis.lua').startDefeat()
  end end
 end
 assert(#c.bosses==1,'Exactly one supported live boss must be loaded.')
 local b=c.bosses[1]
 -- Preserve the independently verified Ocelot implementation and its log.
 if b.actor.name=='revolver.c'then return A.defeatOcelot()end
 if b.actor.name=='psyco.c'and not nativeOnly then
  return dofile(dir..'int-boss-mantis.lua').startDefeat()
 end
 if b.actor.name=='ninja.c'and not nativeOnly then
  return dofile(dir..'int-boss-ninja.lua').startDefeat()
 end
 ready(B,c);sameActor(c.ram,b.actor)
 local P=dofile(dir..'int-boss-experimental.lua');local plan=P.plan(B,c,b)
 -- Validate the complete plan before the first write. These checks catch
 -- changed targets, phases, code, ownership, pending hits and area loads.
 ready(B,c);sameActor(c.ram,b.actor)
 for _,o in ipairs(plan.owners)do
  assert(u32(c.ram+o.work+8)==o.act and u32(c.ram+o.work+12)==o.die,'Target owner changed.')
  assert(u32(o.pointerAddress)==o.pointer,'Boss target changed.')
  if o.parent then assert(u32(o.parent.address)==o.parent.value,'Tank gunner parent changed.')end
 end
 for _,p in ipairs(plan.proofs)do assert(u32(c.ram+(p.pc&amp;0x1fffff))==p.word,'Boss code changed.')end
 local seen={}
 for _,block in ipairs(plan.blocks)do
  local key=block.address..':'..#block.bytes
  if not seen[key]then
   seen[key]=true
   local bytes=assert(readBytes(block.address,#block.bytes,true),'Boss code unavailable')
   assert(#bytes==#block.bytes,'Incomplete boss code read')
   for i=1,#bytes do assert(bytes[i]==block.bytes:byte(i),'Boss code changed.')end
  end
 end
 local function value(v)return v.size==2 and u16(v.address)or u32(v.address)end
 for _,v in ipairs(plan.conditions)do assert(value(v)==v.value,'Boss vulnerability changed; retry.')end
 for _,list in ipairs({plan.writes,plan.notifications})do
  for _,v in ipairs(list)do assert(value(v)==v.before,'Boss state changed; wait briefly and retry.')end
 end
 local written=0
 local function apply(v)
  local ok;if v.size==2 then ok=writeSmallInteger(v.address,v.value)else ok=writeInteger(v.address,v.value)end
  assert(ok,'Boss write failed after '..written..' writes: '..v.label)
  written=written+1
 end
 for _,v in ipairs(plan.writes)do apply(v)end
 -- Publish damage notifications only after health/counters and impact types.
 for _,v in ipairs(plan.notifications)do apply(v)end
 A.last={pid=B.pid,stage=c.stage,boss=plan.boss,profile=plan.profile,tested=false,work=b.actor.offset,writes=written,targets=#plan.notifications}
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/integral-boss-defeat-actions.csv','a+'))
  local success,why=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,pid,area,boss,experimental,actor,field,address,before,requested\n'))end
   for _,list in ipairs({plan.writes,plan.notifications})do for _,v in ipairs(list)do
    assert(f:write(string.format('%s,%d,%s,%s,true,%08X,%s,%X,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),B.pid,c.stage,plan.profile,0x80000000+b.actor.offset,v.label,v.address,v.before,v.value)))
   end end
  end)
  f:close();assert(success,why)
 end)
 if not ok then A.logError=tostring(err)end
 INTBossActions=A
 return A.last
end
return A
]====]):sub(2),
 [ [====[Integral/int-boss-experimental.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Integral roster. Ocelot/Tank/Ninja defeat confirmed; others need live tests.
-- Source work offsets are candidates, accepted only with native RW/decrement
-- evidence. A rejected profile needs encounter research, not relaxed checks.
-- This module only reads/plans. int-boss-actions.lua performs optional writes.
local P={version=1}
P.catalog={
 ['revolver.c']={id='ocelot',name='Revolver Ocelot',stages={s04b=true,s04c=true},tested=true},
 ['m1e1.c']={id='tank',name='M1 tank / Raven',stages={s05a=true},tested=true},
 ['ninja.c']={id='ninja',name='Cyborg Ninja',stages={s08b=true},tested=true},
 ['psyco.c']={id='mantis',name='Psycho Mantis',stages={s07b=true},tested=true},
 ['wolf2.c']={id='wolf',name='Sniper Wolf',stages={s10a=true,s12a=true},testedStages={s10a=true}},
 ['hind.c']={id='hind',name='Hind D',stages={s11g=true}},
 ['valcan.c']={id='raven',name='Vulcan Raven',stages={s15c=true}},
 ['mgrex.c']={id='rex',name='Metal Gear REX (current phase)',stages={s17a=true}},
 ['liquid.c']={id='liquid',name='Liquid Snake',stages={s18a=true}},
 ['jeep_liq.c']={id='escape',name='Liquid (escape chase)',stages={s19b=true}},
}
local function u16(a)return assert(readSmallInteger(a),'Target read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xffffffff end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function record(plan,r,address,size,value,label)
 local before=size==2 and u16(address)or u32(address)
 assert(value&gt;=0 and value&lt;(size==2 and 0x10000 or 0x100000000),'Invalid planned value')
 for _,v in ipairs(plan.writes)do assert(v.address~=address,'Duplicate planned field')end
 plan.writes[#plan.writes+1]={address=address,size=size,value=value,before=before,label=label}
end
function P.plan(B,c,b)
 local profile=assert(P.catalog[b.actor.name],'Boss profile missing')
 assert(profile.stages[c.stage],'Boss/area mismatch')
 assert(profile.id~='ocelot','Ocelot uses the tested action')
 local r,w=c.ram,b.actor.offset
 local plan={boss=profile.name,profile=profile.id,tested=false,ram=r,pid=B.pid,stage=c.stage,actor=b.actor,writes={},notifications={},proofs={},owners={},conditions={},blocks={}}
 local evidence=B.ownership(r,b.actor)
 local function retain(owned)
 for _,v in ipairs(owned.blocks or {})do plan.blocks[#plan.blocks+1]=v end
 for _,v in ipairs(owned.conditions or {})do plan.conditions[#plan.conditions+1]=v end
end
 retain(evidence)
 local function condition(address,size,value)
  plan.conditions[#plan.conditions+1]={address=address,size=size,value=value}
  return value
 end
 local function keep(p)plan.proofs[#plan.proofs+1]=p end
 local function field(offset,value,label,options)
  local e=evidence.fields[offset]
  assert(e and e.read and e.write,'Native read/write proof missing for '..label..'; no changes made')
  if options and options.decrement then assert(e.decrement,'Native decrement proof missing for '..label)end
  local old=s32(r+w+offset);assert(old&gt;=((options and options.minimum)or 0)and old&lt;=((options and options.maximum)or 32767),'Implausible or already finished '..label)
  keep(e.read);keep(e.write);if e.decrement then keep(e.decrement)end
  record(plan,r,r+w+offset,4,value,label)
  return old
 end
 local function targets(actor,owned,requiredParent)
  retain(owned)
  local added=0
  for offset,p in pairs(owned.targets)do
   local ptr=u32(r+actor.offset+offset)
   if ptr&gt;=0x800b64e0 and ptr&lt;0x800b76e0 and (ptr-0x800b64e0)%0x48==0 then
    local t=r+(ptr&amp;0x1fffff);local class,side=u16(t),u16(t+2)
    if side==2 and class&amp;4~=0 then
     condition(t,2,class);condition(t+2,2,side)
     assert(u16(t+6)&amp;4==0,'Boss is processing a hit; wait briefly and retry')
     plan.owners[#plan.owners+1]={work=actor.offset,act=actor.act,die=actor.die,pointerAddress=r+actor.offset+offset,pointer=ptr,parent=requiredParent}
     keep(p);local duplicate=false
     for _,n in ipairs(plan.notifications)do if n.address==t+6 then duplicate=true end end
     if not duplicate then
      local mode=(profile.id=='ninja'or profile.id=='liquid')and 3 or 0
      record(plan,r,t+0x3e,2,mode,'ordinary boss damage mode')
      if profile.id=='hind'or profile.id=='rex'then record(plan,r,t+0x44,4,4,'Stinger impact type')
      elseif profile.id=='wolf'then record(plan,r,t+0x44,4,9,'PSG1 impact type')end
      record(plan,r,t+0x26,2,0,'boss-owned target HP')
      plan.notifications[#plan.notifications+1]={address=t+6,size=2,value=u16(t+6)|4,before=u16(t+6),label='damage notification'}
      added=added+1
     end
    end
   end
  end
  return added
 end
 if profile.id=='tank'then
  -- The director's targets are armor, not the gunners' health. Restrict to
  -- a gunner actor with an explicit parent pointer to this director.
  field(0xe08,1,'remaining tank gunners',{minimum=1,maximum=16,decrement=true})
  field(0xe0c,0,'current gunner health')
  local children=0
  for _,a in ipairs(c.actors)do
   if a.name and a.name:match('^m1e1')and a.name~='m1e1.c'and u32(r+a.offset+0x1ec)==0x80000000+w then
    local n=targets(a,B.ownership(r,a),{address=r+a.offset+0x1ec,value=0x80000000+w})
    if n&gt;0 then children=children+n end
   end
  end
  assert(children&gt;0,'No code-owned active tank gunner target; no changes made')
  -- Tank gunners treat damaged as a damage magnitude. Native thresholds
  -- come from the director's positive HP/divisor settings.
  local hp,divisor=s32(r+w+0xd74),s32(r+w+0xdec)
  assert(hp&gt;0 and hp&lt;=32767 and divisor&gt;0 and divisor&lt;=32767,'Tank damage threshold unavailable')
  assert(s32(r+w+0xf5c)==0,'Tank gunner is in hit recovery; retry when vulnerable')
  condition(r+w+0xd74,4,hp);condition(r+w+0xdec,4,divisor);condition(r+w+0xf5c,4,0)
  for _,n in ipairs(plan.notifications)do n.value=math.max(4,math.floor(hp/divisor));assert(n.value&lt;=32767)end
 elseif profile.id=='wolf'then
  field(0x6fc,1,'Wolf remaining hits',{minimum=1,maximum=64,decrement=true})
  field(0xa40,0,'Wolf health units')
  assert(s32(r+w+0x748)==0 and s32(r+w+0xa54)==0,'Wolf is protected/in hit recovery; retry when vulnerable')
  condition(r+w+0x748,4,0);condition(r+w+0xa54,4,0)
  assert(targets(b.actor,evidence)&gt;0,'No active Wolf damage target')
 elseif profile.id=='hind'then
  field(0x434,1,'Hind remaining missile hits',{minimum=1,maximum=64,decrement=true})
  field(0x654,0,'Hind health')
  assert(s32(r+w+0x50c)==0 and s32(r+w+0x658)==0,'Hind is protected/in hit recovery; retry when vulnerable')
  condition(r+w+0x50c,4,0);condition(r+w+0x658,4,0)
  local y=u16(r+w+0x22);assert(y&gt;0 and y&lt;32768,'Wait for Hind to be airborne')
  condition(r+w+0x22,2,y)
  assert(targets(b.actor,evidence)&gt;0,'No active Hind damage target')
 elseif profile.id=='raven'then
  field(0x900,0,'Raven health')
  assert(targets(b.actor,evidence)&gt;0,'No active Raven damage target')
 else
  -- For undecompiled REX/Liquid code, require runtime TARGET ownership from
  -- GM_FreeTarget calls. Never guess heap addresses from another playthrough.
  -- Only zero a bar's underlying field when native code also writes it.
  if b.binding then field(b.binding.offset,0,'code-derived boss health units')
  elseif profile.id=='ninja'then field(0x19e4,0,'Ninja health units')end
  assert(targets(b.actor,evidence)&gt;0,'No code-owned active boss damage target; no changes made')
 end
 assert(#plan.notifications&gt;0 and #plan.notifications&lt;=12 and #plan.writes&lt;=64,'Unexpected boss target count')
 return plan
end
return P
]====]):sub(2),
 [ [====[Integral/int-boss-mantis.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Mantis owns TARGET+26 health; Meryl's actor/target is independent.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local M={pid=getOpenedProcessID()}
local function u16(a)return assert(readSmallInteger(a))&amp;0xFFFF end
local function u32(a)return assert(readInteger(a))&amp;0xFFFFFFFF end
function M.check(r,a)
 assert(a.name=='psyco.c'and a.offset&gt;=0x10000 and a.offset+0xAE8&lt;0x200000,'Mantis actor differs')
 assert(a.act&gt;=0x800C0000 and a.act&lt;0x801F0000 and a.die==a.act+0x170,'Mantis functions differ')
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Mantis actor changed')
 for _,p in ipairs(M.proofs)do
  local bytes=assert(readBytes(r+(a.act&amp;0x1FFFFF)+p.delta,#p.bytes,true))
  for i=1,#p.bytes do assert(bytes[i]==p.bytes:byte(i),'Integral Mantis health code differs')end
 end
 local evidence=dofile(dir..'int-ownership.lua').ownership(r,a)
 assert(evidence.targets[0x7E0],'Mantis target ownership unavailable')
 local pointer=u32(r+a.offset+0x7E0)
 assert(pointer&gt;=0x800B64E0 and pointer&lt;0x800B76E0 and (pointer-0x800B64E0)%0x48==0,'Mantis target pool differs')
 assert(u16(r+(pointer&amp;0x1FFFFF)+2)==2,'Mantis target side differs')
 return pointer
end
function M.health(r,a)
 local pointer=M.check(r,a);local hp=u16(r+(pointer&amp;0x1FFFFF)+0x26);if hp&gt;=32768 then hp=hp-65536 end
 local maximum=u16(r+0xC3390);assert(maximum&gt;0 and maximum&lt;=32767 and hp&lt;=maximum,'Mantis health range differs')
 return {hp=math.max(0,hp),rawHP=hp,maximum=maximum,target=pointer,visible=u32(r+a.offset+0x850)&amp;0x20~=0,phase=u16(r+a.offset+0x844)}
end
function M.setHealth(hp)
 assert(getOpenedProcessID()==M.pid,'Attached process changed')
 local G=dofile(dir..'int-inventory.lua');local safe=G.context(true)
 local B=dofile(dir..'int-boss-observer.lua');local c=B.inspect()
 assert(c.ram==safe.ram and c.stage=='s07b'and #c.bosses==1 and c.bosses[1].actor.name=='psyco.c','Enter active Mantis combat')
 local a=c.bosses[1].actor;local h=M.health(c.ram,a);local r=c.ram;local t=r+(h.target&amp;0x1FFFFF)
 assert(type(hp)=='number'and hp%1==0 and hp&gt;0 and hp&lt;=h.maximum and h.rawHP&gt;0,'Invalid Mantis health request')
 assert(h.visible,'Wait until Mantis health bar is visible')
 assert(u16(r+0xBD360+0x2A)==0,'Close the menu')
 assert(u16(t+6)&amp;4==0 and u16(t+0x28)==0,'Mantis is processing damage; retry')
 local fresh=G.context(true);assert(fresh.ram==r and fresh.stage==c.stage and getOpenedProcessID()==M.pid,'Encounter changed')
 assert(M.check(r,a)==h.target and u16(t+0x26)==h.rawHP,'Mantis target or health changed')
 assert(u16(t+6)&amp;4==0 and u16(t+0x28)==0,'Mantis damage state changed; retry')
 assert(writeSmallInteger(t+0x26,hp),'Mantis health write failed')
 return {beforeHP=h.rawHP,hp=hp,maximum=h.maximum,work=a.offset,target=h.target}
end
function M.protectMeryl(r,a)
 assert(a.name=='meryl07b.c'and a.act==0x800C9F50 and a.die==0x800CA0F0,'Meryl actor differs')
 for _,p in ipairs(M.protectionProofs)do
  local b=assert(readBytes(r+p.offset,#p.bytes,true));for i=1,#p.bytes do assert(b[i]==p.bytes:byte(i),'Meryl protection native code differs')end
 end
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Meryl changed')
 local e=dofile(dir..'int-ownership.lua').ownership(r,a);assert(e.targets[0x7DC],'Meryl target ownership unavailable')
 local pointer=u32(r+a.offset+0x7DC);assert(pointer&gt;=0x800B64E0 and pointer&lt;0x800B76E0 and (pointer-0x800B64E0)%0x48==0,'Meryl target pool differs')
 local t=r+(pointer&amp;0x1FFFFF);assert(u16(t+2)==2 and u16(t+0x26)&gt;0 and u16(t+0x26)&lt;32768,'Meryl is not alive')
 local previous=u16(t+0x24);local applied=(previous&amp;0xFFFC)|3
 -- Native POWER_CONST keeps vital unchanged. Faint still decreases normally.
 assert(u32(r+a.offset+0x7DC)==pointer,'Meryl target changed')
 if previous~=applied then assert(writeSmallInteger(t+0x24,applied),'Meryl protection write failed')end
 return {work=a.offset,act=a.act,die=a.die,pointer=pointer,address=t+0x24,previous=previous,applied=applied}
end
function M.startDefeat()
 assert(getOpenedProcessID()==M.pid,'Attached process changed')
 assert(not INTMantisDefeat or INTMantisDefeat.stopped,'Mantis assistance already active')
 local G=dofile(dir..'int-inventory.lua');local first=G.context(true);assert(first.stage=='s07b','Enter the Mantis room')
 local B=dofile(dir..'int-boss-observer.lua')
 local T={pid=M.pid,ram=first.ram,started=getTickCount(),hits=0,status='Waiting for Mantis; Meryl protection required'};INTMantisDefeat=T
 local function restore()
  local p=T.protection;if not p then return end;T.protection=nil
  local ok,err=pcall(function()
   assert(getOpenedProcessID()==T.pid);local h=B.reader.read();assert(h.ram==T.ram and h.stage=='s07b')
   if u32(T.ram+p.work+8)==p.act and u32(T.ram+p.work+12)==p.die and u32(T.ram+p.work+0x7DC)==p.pointer and u16(p.address)==p.applied then
    assert(writeSmallInteger(p.address,p.previous),'Meryl restoration failed')
   end
  end)
  if not ok then T.restoreError=tostring(err)end
 end
 function T.stop(reason)
  if T.stopped then return end;T.stopped=true;T.status=reason
  if T.timer then T.timer.Enabled=false;T.timer.destroy();T.timer=nil end
  restore();local row=getAddressList().getMemoryRecordByID(508);if row and row.Active then row.Active=false end
 end
 function T.tick()
  if T.stopped or T.busy then return end;T.busy=true
  if getOpenedProcessID()~=T.pid then T.stop('Stopped: process changed');T.busy=false;return end
  if getTickCount()-T.started&gt;180000 or T.hits&gt;=12 then T.stop('Stopped: Mantis assistance limit reached');T.busy=false;return end
  local ok,err=pcall(function()
   local c=B.inspect();local r=c.ram
   if r~=T.ram or c.stage~='s07b'then T.stop('Stopped: encounter changed');return end
   if u32(r+0xAB3D4)~=0 or c.playerHealth&lt;=0 then T.stop('Stopped: game over');return end
   local mantis,meryl
   for _,a in ipairs(c.actors)do if a.name=='psyco.c'then assert(not mantis);mantis=a elseif a.name=='meryl07b.c'then assert(not meryl);meryl=a end end
   if mantis then
    local h=M.health(r,mantis)
    -- Phase9 is still combat. Only the native death routine's own flag
    -- establishes that the final accepted hit actually started its sequence.
    if u32(r+mantis.offset+0x854)==0x800CF304 and u32(r+mantis.offset+0x84C)&amp;0x10~=0 then
     T.stop('Native Mantis defeat routine started; verify on screen');return
    end
    if h.phase==10 then T.stop('Stopped: native game-over phase');return end
   end
   G.context(true)
   assert(meryl,'Meryl actor unavailable; no boss damage applied')
   local p=T.protection
   if not p or p.work~=meryl.offset or p.pointer~=u32(r+meryl.offset+0x7DC)or u16(p.address)~=p.applied then
    restore();T.protection=M.protectMeryl(r,meryl);p=T.protection
   end
   assert(u16(p.address)==p.applied,'Meryl protection changed')
   if not mantis then T.status='Meryl protected; waiting for Mantis to appear';return end
   local h=M.health(r,mantis);local t=r+(h.target&amp;0x1FFFFF)
   if not h.visible or (h.phase~=2 and h.phase~=4 and h.phase~=6 and h.phase~=8 and h.phase~=9)then T.status='Meryl protected; waiting through scripted/possession phase';return end
   if u16(t)&amp;4==0 or u16(t+6)&amp;4~=0 or u16(t+0x28)~=0 then T.status='Meryl protected; waiting for hittable Mantis';return end
   local result=dofile(dir..'int-boss-actions.lua').defeatCurrentBoss(true)
   T.hits=T.hits+1;T.last=result;T.status='Meryl protected | Mantis phase '..h.phase..' | native hit '..T.hits
  end)
  if not ok then T.status='Waiting safely: '..tostring(err)end
  T.busy=false
 end
 T.timer=createTimer(nil,false);T.timer.Interval=1000;T.timer.OnTimer=T.tick
 T.tick();if T.timer then T.timer.Enabled=not T.stopped end
 return {profile='mantis',pending=true,status=T.status}
end
M.proofs={{delta=0,bytes=('e0ffbd271800b2af219080001c00bfaf1400b1af1000b0af5008429200000000c21102000200401421180000060003240b80023c28b9428c0000000024104300450040140b80023c50ba428c0008033c24104300030040100b80023cb0440308d00542240b80023cc0054224800a42ae9c0051269fd2000c212020020c80023cf4334224a008438e200050268018030021186200980042960000639421200002211043009f96000c540042a6802b030c21204002bdd2000c21202002212000027669000c98074526e007448e40b5000c21280002b400429600000000520042a6e007428e21204002700040a6260043940c80023c1744030cf03343a4e007448e6700468a6400469a6b00478a6800479a2f0086a82c0086b8330087a8300087b885b6000c000000001b36030c212040020e80023ce05b49242300468a2000469a2700478a2400479a030026a9000026b9070027a9040027b91c00bf8f1800b28f1400b18f1000b08f0800e0032000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=368,bytes=('e8ffbd271000b0af1400bfaf3a2f030c21808000d807048e0000000003008010000000007654000c000000003008048e0000000003008010000000007654000c000000003408048e0000000003008010000000007654000c000000003398000c20000426fed2000c9c000426e007048e2cb5000c000000002c08048e'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=-14824,bytes=('d8ffbd271c00b1af218880002400bfaf2000b2af1800b0af5008228e00000000200042305600401000000000e007228e0000000026005084000000000200010600000000218000000009328e000000002a105002020040100c80063c219000029033c294000000000104422c32004014f40822269033c394003c02241a00430002006014000000000d000700ffff0124040061140080013c02004114000000000d000600121000000100033c10004224fb0822a29033c29400c063341a00620002004014000000000d000700ffff0124040041140080013c02006114000000000d00060012180000000000003f006324fc0823a29033c394008002241a00430002006014000000000d000700ffff0124040061140080013c02004114000000000d0006001210000000000000c0ff4224fd0822a2f40822261c000424212840029033c7942130000278e3000c1000a2af232850020a00a0184000a22804004014000000000009228e7a360308c0ff42240009228e0000000023104500000922ae2400bf8f2000b28f1c00b18f1800b08f0800e0032800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=832,bytes=('00b5000c00000000218040001e000012e00750ae212000029d000524020006240c80073c1db7000c0034e7242120000201000524ffff06240c80033c0b80023c903367949cb342241000a0af33b7000c1400a2af'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=-17888,bytes=('e007118e000000002600229628002496060023962110440004006330ce006010260022a60b80023c50ba428c0008033c241043000a004010020002243e002386000000000f006214010012245008028e21900000001042343e330308500802aeb80a028e080003240100422404004314b80a02ae010012243e330308b80a00ae219000002700401600000000e40a02920000000023004010020002243e002386000000001f0062100e80043c335b000cc04f84243f4b030c212040000e80043cc84f8424335b000c1800a2af3f4b030c212040001800a48f21184000110080101c00a3af0f006010000000000400828c00000000000142300a004010000000000400628c000000000001423005004010000000005008028e0100122400044234500802aeac00028600000000060040109c0004261000a0af212800002130a0004cd3000c040007246f004012030002243e0023860000000012006214040002242000042616ca000c340005240c80033c260022969c3363940000000023104300260022a65008028e00000000020042303a0040140d80023c4c08038eb43303085cd2422409006214010002242000042616ca000c350005240c80033c260022969e336394ac33030823104300170062140c80033c4400238e05000224060062140c80023c0c80023c26002396a23342949f3303082318620026002396a03342940000000023186200260023a65008028e0000000002004230180040140d80023c4c08038eb43303085cd2422426002296a23363940000000023104300260022a65008028e00000000020042300b0040140d80023c4c08038e0cd442245c0802ae600800ae660a00a6640a00a6700000a66c0000a6040063344c0803ae212000027a32030c0800052421200002732f030c0600052421200002552b030c88000524ec32030c2120200226002286000000002900401c0b80023cae4d428400000000250040100b80023cd4b3428c00000000210040140d80023c04f34224540802ae4c08028efbff0324580800ae660a00a6640a00a6700000a66c0000a624104300f33303084c0802ae8432030c21200002212000027a32030c212800000d80023c4c08038e94d542245c0802ae600800ae660a00a6640a00a6700000a66c0000a6040063344c0803ae3e00229621202002ec32030c680a02a62c00bf8f2800b28f2400b18f2000b08f0800e0033000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=-2024,bytes=('e8ffbd271000b0af218080000900a0141400bfaf0d80023c04ed4224540802ae580800ae660a00a6640a00a6700000a66c0000a6a92c030c21200002ff32030c21200002e007028e0c80033c2600448492336294000000002a104400190040140b80053c0010043cccb3a28c4c08038e251044000400633012006014ccb3a2ac5008028e03000324460803a610004234b331030c500802ae0d80023c4c08038e68f74224540802ae580800ae660a00a6640a00a6700000a66c0000a6100063344c0803ae1400bf8f1000b08f0800e0031800bd270800e00300000000e8ffbd271000b0af218080000e00a0141400bfaf4e30030c0400052421200002010005240d80023ca4db4224540802ae580800ae660a00a6640a00a6700000a62732030c6c0000a6ff32030c21200002a92c030c212000020e80023cb05b468c000000000000c28c0000000000104230090040140b80053ce007028e0c80033c2600448494336294000000002a10440028004014000000000010043cccb3a28c4c08038e251044000400633021006014ccb3a2ac0000c28c0000000000084230050040140c80033c212000024e30030c080005240c80033ce007048e9433639426008284000000002a1043000200401005000224260083a4460802a60d80023cf8fb4224540802ae4c08028e5008038e580800ae660a00a6640a00a6700000a66c0000a610004234100063344c0802ae500803ae1400bf8f1000b08f0800e0031800bd270800e00300000000e8ffbd271000b0af218080000b00a0141400bfaf020005240d80023ca4db4224540802ae580800ae660a00a6640a00a6700000a62732030c6c0000a6a92c030c21200002ff32030c212000020e80023cb05b468c000000000000c28c0000000000084230090040140b80053ce007028e0c80033c2600448496336294000000002a10440028004014000000000010043cccb3a28c4c08038e251044000400633021006014ccb3a2ac0000c28c0000000000084230050040140c80033c212000024e30030c080005240c80033ce007048e9633639426008284000000002a1043000200401007000224260083a4460802a60d80023c74074224540802ae4c08028e5008038e580800ae660a00a6640a00a6700000a66c0000a610004234100063344c0802ae500803ae1400bf8f1000b08f0800e0031800bd270800e00300000000e0ffbd271000b0af218080001400b1af2188a0001d0020161800bfaf0c80023c90334524e007048e0600a39426008284000000002a1062000500401000000000260083a40600a29400000000000902ae212000020d80023cf0ef4224540802ae580800ae660a00a6640a00a6700000a68432030c6c0000a62120000203000524010002242732030cec0802a6a92c030c21200002ff32030c212000022000222a0d0040100b80023cb8774b242300088a2000089a2700098a2400099a030068a9000068b9070069a9040069b9b8774224800c0324180043ace007028e0c80033c2600448498336294000000002a1044002c004014000000004c08028e000000000400423027004014212000025008028e09001124460811a6100042343a2f030c500802ae4c08028e0000000001004230090040147fff03249c00048e000000002800828c0000000024104300280082ac01000224640802ae212000020cfe05241efb0624ac2d030ca00007248432030c2120000221200002040005240d80023cacdc4224540802ae580800ae660a00a6640a00a6700000a66c0000a62732030cec0811a6a92c030c212000021800bf8f1400b18f1000b08f0800e0032000bd27e8ffbd271000b0af1400bfafa92c030c21808000ff32030c212000021400bf8f1000b08f0800e0031800bd27e8ffbd271000b0af218080001f00a0141400bfaf765f030c000000000b80023c0a7840a401000224fbff04240b80033c640802ae4c08028e20ba638c241044004c0802ae0000658c212000022800a28c7fff0324241043002800a2ac0d80023c84f6422421280000540882ac580880ac660a80a4640a80a4700080a42d2c030c6c0080a41a2c030c212000001400bf8f1000b08f0800e0031800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=-704,bytes=('e8ffbd271000b0af1400bfafa92c030c21808000ff32030c212000021400bf8f1000b08f0800e0031800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=-504,bytes=('e8ffbd271000b0af1400bfaff22b030c218080004331030c212000020200023c4808058eff7042342a104500020040140100a224480802ae44080386000000000b00622c320040100e80023c4450422480180300211862000000628c0000000008004000000000006342030c212000025c4403080b80023c9342030c212000025c4403080b80023c9b42030c212000025c4403080b80023cd042030c212000025c4403080b80023cd242030c212000025c4403080b80023c2343030c212000025c4403080b80023c2543030c212000025c4403080b80023c7343030c212000025c4403080b80023c7543030c212000025c4403080b80023ce543030c212000025c4403080b80023cf043030c212000020b80023cd4b3428c000000000c0040140b80023cae4d428400000000080040100e80023cb05b428c000000000000428c00000000080042300900401000000000440802860a000324050043102128000001000224440803a659440308480802ae9f31030c21200002682f030c212000021a31030c212000024c08028e000000000400423008004010000000006008058e5c08038e803ea228090040100100a2248b440308600802ae5808058e5408038e803ea228020040100100a224580802ae09f8600021200002c131030c21200002ec2f030c212000021400bf8f1000b08f0800e0031800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=-8016,bytes=('b8ffbd273800b2af219080003c00b3af2198a0004000bfaf3400b1af6d0060163000b0afb331030c00000000ff01043c06ff843412cb000c2128000021204002212800000c80023c28dd40ac0a80023c44f440ac0a80023c34f440ac0a80023c0a80033c9cf440ac4c08428e0b80063c80f460ac100042344c0842aeccb3c28c0a10033c25104300ccb3c2ac0b80063c50bac28c0004033c2510430050bac2ac5008428ef7ff0324241043007a32030c500842ae3a2f030c212040021a2c030c21200000212040022d2c030c212800009c00448e000000002800828c7fff032424104300280082acaa0043861600022405006210212840009c0044262130000035d3000c0400072421204002552b030c890005242000b127212020022800a5271000a627dc0503240b80023c2300488a2000489a2700498a2400499a2300a8ab2000a8bb2700a9ab2400a9bb2200a3a710ba4b24030068890000689907006989040069992b00a8ab2800a8bb2f00a9ab2c00a9bb505b000c2a00a3a7605b000c1000a4271000a4271800b0272128000221304000775b000cdc0507242120200221280002505b000c6c0a46260b80023c9cb34b2403006889000068990700698904006999670048aa640048ba6b0049aa680049bab400428600000000e80342280200401001000224a00842aeb400428600000000f40142280200401002000224a00842ae21000224050062122b00022403006212370002240500621600000000200044263300052471ca000c01000624200044260b80053c10baa5240b80033c010002240a7862a40b80023cb8774b246f0a488a6c0a489a730a498a700a499a030068a9000068b9070069a9040069b9505b000c1000a627be5b000c1000a4270b80033c0b80043cf4b9638c20ba848c4e0062a40000838c000000002800628c0000000080004234280062ac640a4386000000001200601420000224b6004286000000002700401017000224aa00438600000000050062109c004426212840002130000035d3000c04000724640a429600000000010042249a3d0308640a42a60300621421200000ea88030c30000524640a42966000032401004224640a42a600140200031402000e00431421204002ffff05245008828c2118a000460883a4100042344e30030c500882acfffb043c0b80033c50ba628cffff84342410440050ba62ac4000bf8f3c00b38f3800b28f3400b18f3000b08f0800e0034800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
M.protectionProofs={{offset=0xC9F50,bytes=('e0ffbd271800b2af219080000b80023c50ba428c0008033c1c00bfaf1400b1af24104300040040101000b0af0b80023ce4270308d00542240b80023cc0054224dc0842ae9c0051269fd2000c21202002200050269f96000c21200002bdd2000c21202002212000027669000c98074526dc07448e40b5000c21280002b4004396000000000014030003240200f401822802004010520043a6f4010424dc07428e0c80033c120044a46e084296fc32632480100200211043000000429498004396660844862110430006008104540042a677004282000000000200401000000000660840a66608429621204002700040a6e0ff4224660842a60e80023cb85b49242300468a2000469a2700478a2400479a030026a9000026b9070027a9040027b95127030c340840aedc07448e6700468a6400469a6b00478a6800479a2f0086a82c0086b8330087a8300087b885b6000c00000000811d030c2120400266004296660843966c00449621104300ff0f8430660042a601088228030040146c0044a600f082246c0042a61c00bf8f1800b28f1400b18f1000b08f0800e0032000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x2DA14,bytes=('d8ffbd271400b1af218880002000bfaf1c00b3af1800b2af1000b0af000022960000000008004230030040140b80023c16b70008211000008407938fe06452240b800a3c9cb34a2503004789000047990700488904004899370027aa340027ba3b0028aa380028ba7200601a3a0020a6400050266b003212000000a60000429600000000080042306600401021204002c0b4000c212820026200401000000000d0ff058610002486c8ff0386080022862128a4002320430007008004000000002328a4000900a1042130a00021280000c0b600082130a00021208500030081042330040021200000233004004200c01021100000d4ff058614002486ccff03860c0022862128a4002320430007008004000000002328a4000900a1042120a00021280000d5b600082120a00021208500030081042320040021200000232004002d00801021100000fcff0296000000000200423028004014010002240200c1042118c000231803000200810421108000231002002a1043000e004014c2170400c21706002110c200340023964330020021186600340023a6f4ff029604000324231046000e00c018f4ff02a6fdb600080200032421108200380023964320020021186400380023a6f8ff0296030003242310440002008018f8ff02a601000324fcff0296000000000100423002004010010002243a0023a60a00401000000000c6ff02960000000008004234c6ff02a6060022960200239608004234060022a6000003a648001026ffff732691ff601e480052260600229600000000080042302b1002002000bf8f1c00b38f1800b28f1400b18f1000b08f0800e0032800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
return M
]====]):sub(2),
 [ [====[Integral/int-boss-ninja.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Integral Ninja health units, separate from collision TARGET vital.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local N={maximum=255,pid=getOpenedProcessID()}
local function u32(a)return assert(readInteger(a))&amp;0xFFFFFFFF end
local function u16(a)return assert(readSmallInteger(a))&amp;0xFFFF end
function N.check(r,a)
 assert(a.name=='ninja.c'and a.offset&gt;=0x10000 and a.offset+0x1B40&lt;0x200000,'Ninja actor bounds differ')
 assert(a.act&gt;=0x800C0000 and a.act&lt;0x801F0000 and a.die==a.act+0x534,'Ninja functions differ')
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Ninja actor changed')
 for _,p in ipairs(N.proofs)do
  local bytes=assert(readBytes(r+(a.act&amp;0x1FFFFF)+p.delta,#p.bytes,true))
  for i=1,#p.bytes do assert(bytes[i]==p.bytes:byte(i),'Integral Ninja health code differs')end
 end
end
function N.health(r,a)
 N.check(r,a)
 local hp=u32(r+a.offset+0x19E4);assert(hp&lt;=255,'Ninja health outside native range')
 return {hp=hp,maximum=255,bar=hp*4,phase=u32(r+a.offset+0x19C4)}
end
function N.setHealth(hp)
 assert(getOpenedProcessID()==N.pid,'Attached process changed; reopen Ninja controls')
 assert(type(hp)=='number'and hp%1==0 and hp&gt;0 and hp&lt;=255,'Choose Ninja HP from 1 to 255')
 local G=dofile(dir..'int-inventory.lua');local safe=G.context(true)
 local B=dofile(dir..'int-boss-observer.lua');local c=B.inspect()
 assert(c.ram==safe.ram and c.stage=='s08b'and #c.bosses==1 and c.bosses[1].actor.name=='ninja.c','Enter the live Ninja encounter')
 local a=c.bosses[1].actor;local h=N.health(c.ram,a);assert(h.hp&gt;0,'Ninja has reached the final sequence')
 local r=c.ram
 assert(u32(r+0xBD360+8)==0x800386A4 and u32(r+0xBD360+12)==0x800387E8 and u16(r+0xBD360+0x2A)==0,'Close the menu')
 local fresh=G.context(true);assert(fresh.ram==r and fresh.stage==c.stage and getOpenedProcessID()==B.pid,'Encounter changed')
 N.check(r,a);assert(u32(r+a.offset+0x19E4)==h.hp,'Ninja health changed; retry')
 assert(writeInteger(r+a.offset+0x19E4,hp),'Ninja health write failed')
 return {beforeHP=h.hp,hp=hp,maximum=255,work=a.offset}
end
function N.startDefeat()
 assert(getOpenedProcessID()==N.pid,'Attached process changed')
 assert(not INTNinjaDefeat or INTNinjaDefeat.stopped,'Ninja defeat assistance already active')
 local B=dofile(dir..'int-boss-observer.lua');local first=B.inspect()
 assert(first.stage=='s08b'and #first.bosses==1 and first.bosses[1].actor.name=='ninja.c','Enter the Ninja encounter')
 N.health(first.ram,first.bosses[1].actor)
 local T={pid=N.pid,ram=first.ram,work=first.bosses[1].actor.offset,hits=0,started=getTickCount(),status='Waiting for a hittable Ninja phase'}
 INTNinjaDefeat=T
 function T.stop(reason)
  if T.stopped then return end;T.stopped=true;T.status=reason
  if T.timer then T.timer.Enabled=false;T.timer.destroy();T.timer=nil end
  local row=getAddressList().getMemoryRecordByID(508);if row and row.Active then row.Active=false end
 end
 function T.tick()
  if T.stopped or T.busy then return end;T.busy=true
  if getOpenedProcessID()~=T.pid then T.stop('Stopped: process changed');T.busy=false;return end
  if getTickCount()-T.started&gt;180000 or T.hits&gt;=24 then T.stop('Stopped: bounded Ninja assist limit reached');T.busy=false;return end
  local ok,err=pcall(function()
   local c=B.inspect()
   if c.ram~=T.ram or c.stage~='s08b'then T.stop('Stopped: encounter changed');return end
   if #c.bosses~=1 or c.bosses[1].actor.offset~=T.work then T.stop('Stopped: Ninja actor ended or changed');return end
   local a=c.bosses[1].actor;local h=N.health(c.ram,a);local w=c.ram+a.offset
   -- Verified native completion branch: final phase, three finishing hits,
   -- stage callback queued by the game itself. Never write these state fields.
   if h.phase==7 and u32(w+0x19E0)&gt;=3 and u32(w+0x19B8)==3 then
    T.stop('Native Ninja completion sequence reached; verify on screen');return
   end
   local G=dofile(dir..'int-inventory.lua');G.context(true)
   local e=B.ownership(c.ram,a);assert(e.targets[0x8C4],'Ninja target ownership unavailable')
   local pointer=u32(w+0x8C4);assert(pointer&gt;=0x800B64E0 and pointer&lt;0x800B76E0 and (pointer-0x800B64E0)%0x48==0,'Ninja target pool differs')
   local t=c.ram+(pointer&amp;0x1FFFFF)
   if u16(t+2)~=2 or u16(t)&amp;4==0 or u16(t+6)&amp;4~=0 then T.status='Waiting: Ninja currently unhittable';return end
   if u32(w+0x19F0)~=0 then T.status='Waiting: Ninja hit recovery';return end
   -- Reuse the guarded native planner; it rechecks code, state and targets.
   local result=dofile(dir..'int-boss-actions.lua').defeatCurrentBoss(true)
   T.hits=T.hits+1;T.last=result;T.status='Native physical hit '..T.hits..' | Ninja phase '..h.phase
  end)
  if not ok then T.status='Waiting: '..tostring(err)end
  T.busy=false
 end
 T.timer=createTimer(nil,false);T.timer.Interval=1000;T.timer.OnTimer=T.tick;T.timer.Enabled=true
 return {profile='ninja',pending=true,status=T.status}
end
N.proofs={{delta=0,bytes=('d8ffbd271800b0af218080001c00b1af2000bfaf4720030c200011269f96000c21202002e2d2000c9c000426212020027669000c98070526c436030c21200002d807028e000000000700401400000000c408048e40b5000c21282002c408048e85b6000c00000000d819028ed807038e0100422417006014d81902aee419028e00000000030041040c80063ce41900aee419028e8c33c38c000000002a10430002004010ffff62248c33c2ac100004241c0005240c80023c8c33c68ce419078e803342241000a2af803006005de3000c803807007220030c212000022000bf8f1c00b18f1800b08f0800e0032800bd27e0ffbd271f000524020006240c80073c1c00bfaf1800b0afc408908c9033e7241db7000c212000022120000201000524ffff0624ff0007242110e0001000a2af0c80023c9833422433b7000c1400a2af21200002ffff0524ff000624213800002db7000c1000a0af1c00bf8f1800b08f0800e0032000bd27c8ffbd273000b4af21a080002c00b3af20009326212060023400bfaf2800b2af2400b1af6796000c2000b0af4f004004ffff02245a82000c70000424640004245a82000c2180400021206002212800027098000c21304000212060028f98000c050005242120600204000524020002249198000c590062a20e80043c40378424335b000c9c0092260e80103c4c37102621200002335b000c2188400021204002212820022d03062486d2000c213840002dd3000c21204002335b000c21200002212040028001852621304000d0018726340482261000a2af980682261400b3afc2d3000c1800a2af212040029807912611d3000c212820020e80043c54378424335b000cdc07902621200002212840006d00062486d2000c213800002120000211d3000c21282002212000022128400217d3000c040006242120400204000524fc1990265356030c213000022120400208000524213000025356030c201a82ae241a82ae21100000fc1980ae3400bf8f3000b48f2c00b38f2800b28f2400b18f2000b08f0800e0033800bd274c00828c000000000800428c000000000000428c000000000e004a841800498c1100422903004014200987240800e003ffff022460198aa422004019214000000000238500000000ffff62242000422cf6ff40100000e3ac0400268d14006018212800002118e0000600c4240000c29400000000040062a4feff82940800c624060062a4fcff82940100a524080062a400008294080084240a0062a40000e28c000000002a10a200f0ff4014080063240401e724010008252a100a01e0ff4014080029250800e00321100000d8ffbd271c00b1af2188800012000424010005240cfe0324601a2726f4010624681a22262000bfaf1800b0af601a23a60200e0a40400e3a4681a26a6020040a4040043a4701a2226701a23a6020040a4040046a4781a2226781a26a6040046a421300000020040a4af6e000c1000a0af2180400008000012211000029d60000c212000020b80023cb0b9428c00000000280002a62110000209004010801a22ae0e80043c335b000c5c3784240c76000c21204000213840000300e01421480000e1210308ffff022409000c242e000b2434000a24214000024000028d0000000003004ca007004ba004004aa005004aa006004aa00800e5900a00e4900900e3900b00e6902120a4000d0043a0150043a0211866000c0045a0140044a01c0045a01d0043a0240044a0250043a00400e39400000000160043a40600e394010029250e0043a402002229e3ff401404000825212020024536030c02000524211000002000bf8f1c00b18f1800b08f0800e0032800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=2776,bytes=('03006014c01900ae55230308c41900ae05000224c41902ae21100000ff00032401000424e41903ae'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=17172,bytes=('c8ffbd271800b0af218080002c00b5af21a8a0002800b4af010014241c00b1af200011263000bfaf2400b3af2000b2af5225030cfc1914ae06004010000000003c1a028e0000000021105400be3103083c1a02aec408138e2e00a016010004240e80053c3c39a5242c1b0292e419068e3c1a078e2330c200e62e020ce41906ae9c001226212040022130000012000224a41902ae0c80023cc433458435d3000c04000724212020028900052471ca000c010006243e0062860000000004005410212020023400052471ca000c01000624281a0296000000000a0022a6281a029610000424245c000c4e0022a6212840000200a6241000c2280200401421204002f2ffa624040007241000a0af5860030c1400a0afb6000286000000000b00401001000224a81902ae1e000224f01902ae0d80023c389b42243c1a00ae941902ae9c1900ae700000a66c0000a63c1a028e0000000002004228090040100a00a22a0700401000000000c408038e0000000000006294000000001f004234000062a43000bf8f2c00b58f2800b48f2400b38f2000b28f1c00b18f1800b08f0800e0033800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=17592,bytes=('e0ffbd271000b0af218080001400b1af200011261b00a0141800bfaf9c000426213000002d1b0592e419028e13000324a41903ae23104500e41902ae0c80023cc633458435d3000c04000724212020028a00052471ca000c01000624212020023400052471ca000c01000624281a0296000000000a0022a6281a0296000000004e0022a6b6000286000000000b00401001000224a81902ae1e000224f01902ae0d80023c389b42243c1a00ae941902ae9c1900ae700000a66c0000a61800bf8f1400b18f1000b08f0800e0032000bd27d8ffbd271000b0af218080001400b1af2188a0002000bfaf1c00b3af1800b2afc408138e0a002016010012249c0004262130000015000224a41902ae0c80023c'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=22412,bytes=('c408838c0000000006006594000000000400a23004004010341a80ac3e0062840800e003341a82ac0200a23006004010240002243e006384000000000200621406000224341a82ac0800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=29416,bytes=('e8ffbd271000b0af218080001400bfaf341a028e0000000028004010ffff43240600622c230040100e80023c9039422480180300211862000000628c0000000008004000000000000c80023c21200002ba38030c483440ac07000224c81902ae7f3d0308050002240c80023c483440ac07000224c81902ae7f3d030817000224070002240c80043cc81902ae4834828c17000324cc1903ae01004224803d0308483482ac07000224c81902ae22000224cc1902ae943d030801000224cc19028e00000000fdff42240200422c0d004014211000000b80023cccb3428c0000000001004230060040100100022409000324c81903ae1d000324943d0308cc1903ae211000001400bf8f1000b08f0800e0031800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=40692,bytes=('e8ffbd271000b0af218080001400bfafcc19028e000000000d00401400000000a03e030c000000000900401021200002e01900ae6f3a030cdc1900ae01000224c81902ae05000224cc1902aed01900ae1400bf8f1000b08f0800e0031800bd27e8ffbd271000b0af218080001400bfafcc19038e170002240e0062101800622805004010050002244100621000000000c3480308000000001c00022424006210230002242800621000000000c348030800000000a841030c212000023d00401001000224381a038e000000000c006214000000002c1a028e00000000b0044228040040100300022405000224a0480308c81902aec81902aea048030808000224e419028e00000000060042280500401007000224c41902aec81900aec2480308cc1900ae23000224c2480308cc1902aeba40030c212000021e00401023000224c2480308cc1902ae5441030c212000020d004010160002242c1a028e00000000b00442280300401005000224b6480308c81902ae03000224c81902ae08000224c2480308cc1902aec3480308b01902ae783f030c212000020600401003000224c81902ae08000224cc1902aed41900aed01900ae1400bf8f1000b08f0800e0031800bd27e0ffbd271000b0af218080001800bfaf1400b1afcc19038e1c001124230071101d0062280500401017000224080062100100022403490308000000001d00022413006210010002240349030800000000081a02ae'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=43852,bytes=('e0ffbd271000b0af218080001800bfaf1400b1afcc19038e17000224050062101d0002242b00621000000000a34b03080000000001001124081a11aea841030c212000022500401000000000e019028e000000000300422817004014000000001938030c212000028c1a048e1b000224cc1902ae03000224c81911ae13008004b81902ae0b80023cd4b3428c000000000e0040140b80023cae4d4284000000000a00401800000000cb7f000c21280000a34b0308d01900ae6f3a030c2120000205000224c81911aecc1902aea34b0308d01900ae4c41030c212000021800bf8f1400b18f1000b08f0800e0032000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=51568,bytes=('e8ffbd271000bfafc819838c000000000a00622c220040100e80023c003c422480180300211862000000628c0000000008004000000000007847030c000000001d530308000000003c4e030c000000001d53030800000000d74f030c000000001d530308000000003451030c000000001d53030800000000ad4a030c000000001d53030800000000774a030c000000001d53030800000000a84b030c000000001000bf8f000000000800e0031800bd27e8ffbd271000bfafc819838c02000224120062100300622805004010000000000a006010000000004253030800000000060002240d006210070002240f006210000000004253030800000000e747030c0000000042530308000000000750030c0000000042530308000000004b51030c000000004253030800000000ff4a030c000000001000bf8f000000000800e0031800bd27e8ffbd271000b0af218080001400bfafc819038e020002240f006210030062280500401006000224070060100000000062530308000000000b006210000000006253030800000000584c030c2120000262530308000000004a50030c2120000262530308000000008e51030c21200002c019028e0000000004004234c01902ae1400bf8f1000b08f0800e0031800bd27e8ffbd271000bfafc819838c01000224120062100200622805004010000000000a006010000000008b53030800000000060002240d006210070002240f006210000000008b530308000000004148030c000000008b530308000000007e4e030c000000008b53030800000000f851030c000000008b530308000000004f4b030c000000001000bf8f000000000800e0031800bd27e8ffbd271000bfafc819838c01000224120062100200622805004010000000000a00601000000000b053030800000000060002240d006210070002240f00621000000000b0530308000000005648030c00000000b053030800000000a14e030c00000000b0530308000000002152030c00000000b0530308000000006c4b030c000000001000bf8f000000000800e0031800bd27e8ffbd271000b0af218080001400bfafc419038effff0224b41902aeb01902aec01900ae081a00ae201b02ae0800622c260040100e80023c283c422480180300211862000000628c0000000008004000000000006152030c21200002e7530308000000008d52030c21200002e753030800000000bd52030c21200002e753030800000000f552030c21200002e7530308000000002153030c21200002e7530308000000004653030c21200002e7530308000000006a53030c21200002e7530308000000008f53030c21200002d419028e0000000001004224d41902ae1400bf8f1000b08f0800e0031800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=112428,bytes=('b4f50c8094f50c80ccf50c80ccf50c8000f60c80f0f50c80'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=113052,bytes=('0c4c0d801c4c0d80744c0d802c4c0d80744c0d80744c0d803c4c0d804c4c0d806c4c0d805c4c0d80244f0d80344f0d80444f0d80544f0d80644f0d80744f0d80844f0d80944f0d80'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
return N
]====]):sub(2),
 [ [====[Integral/int-boss-observer.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Boss detection, native health-bar discovery and local recordings. Target reads only.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local D=dofile(dir..'int-discovery.lua')
local B={pid=R.pid,reader=R,bindings={},captures=0,version=1}
local catalog=dofile(dir..'int-boss-experimental.lua').catalog
B.catalog=catalog
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xffffffff end
local function psx(p,n)assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'PSX pointer invalid');return p&amp;0x1fffff end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function binary(r,o,n)
 assert(o&gt;=0 and n&gt;=0 and o+n&lt;=0x200000,'Capture outside RAM')
 local out={}
 for j=0,n-1,4096 do local k=math.min(4096,n-j);local t=assert(readBytes(r+o+j,k,true));assert(#t==k);out[#out+1]=string.char(table.unpack(t))end
 return table.concat(out)
end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function isBranch(w)return op(w)==1 or (op(w)&gt;=4 and op(w)&lt;=7)or op(w)==2 or op(w)==3 or (op(w)==0 and ((w&amp;63)==8 or (w&amp;63)==9))end
local function copy(t)local r={};for k,v in pairs(t)do r[k]=v end;return r end
local function destination(w)
 if op(w)==0 then return rd(w)end
 if (op(w)&gt;=8 and op(w)&lt;=15)or (op(w)&gt;=32 and op(w)&lt;=39)then return rt(w)end
end
-- Conservative backwards slice: only a direct work-field load, a move and/or
-- a left shift are accepted. Branches, calls and complex arithmetic reject it.
local function expression(words,aliases,at,reg,depth)
 if (depth or 0)&gt;5 then return nil end
 if reg==0 then return {kind='constant',value=0}end
 for i=at,math.max(1,at-24),-1 do
  local w=words[i];if isBranch(w)then return nil end
  if destination(w)==reg then
   if op(w)==35 then
    local base=aliases[i][rs(w)]
    if base~=nil and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     local offset=base+signed(w&amp;0xffff)
     if offset&gt;=0x20 and offset&lt;=0x4000 and offset%4==0 then return {kind='field',offset=offset,scale=1}end
    end
   elseif op(w)==9 and rs(w)==0 then return {kind='constant',value=signed(w&amp;0xffff)}
   elseif op(w)==13 and rs(w)==0 then return {kind='constant',value=w&amp;0xffff}
   elseif op(w)==0 then
    local f=w&amp;63
    if (f==33 or f==37)and (rs(w)==0 or rt(w)==0)then
     return expression(words,aliases,i-1,rs(w)==0 and rt(w)or rs(w),(depth or 0)+1)
    elseif f==0 and rs(w)==0 then
     local e=expression(words,aliases,i-1,rt(w),(depth or 0)+1);local shift=(w&gt;&gt;6)&amp;31
     if e and shift&lt;=4 then if e.kind=='field'then e.scale=e.scale*(1&lt;&lt;shift)else e.value=e.value*(1&lt;&lt;shift)end;return e end
    end
   end
   return nil
  end
 end
end
local function proof(r)
 return binary(r,0x38D74,108)==('d8ffbd27214080002148a0002150c00000040324212800013800a48f0b80023cccb3428c213020011000a7af213840012000bfaf1400a3af008042341800a4af0a80043c0b80013cccb322ac19fd000cd0e28424ede2000c000000002000bf8f000000000800e0032800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)
 and binary(r,0x38DE0,72)==('e0ffbd27211880002140a0002148c0000a80043cd0e28424212860003000a28f213000011000a7af213820011800bfaf02fd000c1400a2af1800bf8f000000000800e0032000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)
end
function B.discoverBar(r,actor)
 if not proof(r)then return nil,'Resident health-bar wrapper fingerprint differs'end
 local queue={actor.act};local visited={};local found={};local count=0
 while #queue&gt;0 and count&lt;24 do
  local fn=table.remove(queue,1)
  if not visited[fn]and fn&gt;=0x800c0000 and fn&lt;0x801f0000 and fn%4==0 then
   visited[fn]=true;count=count+1
   local code=binary(r,psx(fn),math.min(0x600,0x200000-psx(fn)));local words={};local aliases={};local alias={[4]=0}
   local stop=false
   for i=1,#code//4 do
    local w=string.unpack('&lt;I4',code,(i-1)*4+1);words[i]=w;aliases[i]=copy(alias)
    -- The previous instruction's call has this instruction as its delay slot.
    local prior=words[i-1]
    local dest=destination(w);local v
    if op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if rt(w)==0 then v=alias[rs(w)]elseif rs(w)==0 then v=alias[rt(w)]end
    elseif op(w)==9 and alias[rs(w)]~=nil then v=alias[rs(w)]+signed(w&amp;0xffff)end
    if dest and dest~=0 then alias[dest]=v end
    if prior and op(prior)==3 then
     local callee=((prior&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if callee==0x80038d74 or callee==0x80038de0 then
      -- Exclude the JAL itself from the backwards slice, but include a
      -- register assignment in its delay slot when present.
      local arg=callee==0x80038d74 and 7 or 6
      local e
      if destination(w)==arg then
       local short={w};local aa={aliases[i]};e=expression(short,aa,1,arg)
       if not e and op(w)==0 and (w&amp;63)==0 then
        local source=expression(words,aliases,i-2,rt(w));local shift=(w&gt;&gt;6)&amp;31
        if source and source.kind=='field'and shift&lt;=4 then source.scale=source.scale*(1&lt;&lt;shift);e=source end
       elseif not e and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)and (rs(w)==0 or rt(w)==0)then
        e=expression(words,aliases,i-2,rs(w)==0 and rt(w)or rs(w))
       end
      else e=expression(words,aliases,i-2,arg)end
      local maximum=1024
      if callee==0x80038de0 then
       local mx=destination(w)==7 and expression({w},{aliases[i]},1,7)or expression(words,aliases,i-2,7)
       if not mx or mx.kind~='constant'or mx.value~=1024 then maximum=nil end
      end
      if e and e.kind=='field'and e.scale&lt;=16 and maximum then
       local key=e.offset..':'..e.scale;found[key]={offset=e.offset,scale=e.scale,maximum=maximum,callPC=fn+(i-2)*4,fn=fn}
      end
     elseif alias[4]==0 and callee&gt;=0x800c0000 and callee&lt;0x801f0000 then queue[#queue+1]=callee end
     for j=2,15 do alias[j]=nil end;alias[24]=nil;alias[25]=nil
    end
    if stop then break end
    if op(w)==0 and (w&amp;63)==8 and rs(w)==31 then stop=true end
   end
  end
 end
 local list={};for _,v in pairs(found)do list[#list+1]=v end
 if #list~=1 then return nil,'Health-bar field not uniquely resolved ('..#list..')'end
 return list[1]
end
function B.actors(r)
 local ok,root=pcall(D.actorRoot,r)
 if not ok then
  -- Liquid uses a different Snake actor. Validate the resident list sentinels
  -- rather than guessing its CONTROL-to-actor offset from the normal Snake.
  root=0xacc18
  for level=0,8 do
   local s=root+level*0x44;local e=s+0x20
   assert(u32(r+s)==0 and u32(r+s+8)==0 and u32(r+s+12)==0 and u32(r+e+4)==0 and u32(r+e+8)==0 and u32(r+e+12)==0,'Actor-list root unavailable')
   psx(u32(r+s+4),32);psx(u32(r+e),32)
  end
 end
 local out={}
 for level=0,8 do
  local start=root+level*0x44;local finish=start+0x20;local previous=start;local p=u32(r+start+4);local seen={}
  for n=1,512 do
   local o=psx(p,32)
   if o==finish then assert(u32(r+finish)==0x80000000+previous,'Actor tail changed');break end
   assert(not seen[o],'Actor cycle');seen[o]=true
   assert(u32(r+o)==0x80000000+previous,'Actor list changed')
   local act,die,np=u32(r+o+8),u32(r+o+12),u32(r+o+20)
   if act&gt;=0x800c0000 and act&lt;0x80200000 and die&gt;=0x800c0000 and die&lt;0x80200000 and np&gt;=0x80000000 and np&lt;0x80200000 then
    out[#out+1]={offset=o,act=act,die=die,name=readString(r+psx(np),48),level=level}
   end
   previous=o;p=u32(r+o+4);assert(n&lt;512,'Actor limit')
  end
 end
 return out
end
function B.ownership(r,actor)
 local e=dofile(dir..'int-ownership.lua').ownership(r,actor)
 if actor.name=='wolf2.c'and actor.act==0x800D6C50 then
  return dofile(dir..'int-boss-wolf.lua').augment(r,actor,e)
 end
 local f=e.fields[0xE0C]
 if actor.name=='m1e1.c'and not(f and f.read and f.write)then
  return dofile(dir..'int-boss-tank.lua').augment(r,actor,e,B.actors(r))
 end
 return e
end
function B.ocelot(r,a,b)
 local ok,v=pcall(function()return dofile(dir..'int-boss.lua').inspect()end)
 if not ok or v.ram~=r or v.work~=a.offset then b.reason='Ocelot detailed layout unavailable';return end
 b.hp=v.hp;b.maxHP=v.maximum;b.target=v.target
 b.phaseID=v.phase;b.phase=({'Positioning','Movement','Firing','RELOADING','Defeated','Transition','Opening'})[v.phase+1]
 b.stateCounter=v.counter
 b.evidence='Integral Ocelot health and defeat confirmed in gameplay'
end
function B.inspect()
 local h=R.read();local r=h.ram
 assert(u32(r+0xab3d0)==0 and u32(r+0xaba38)~=0,'Area loading; previous boss readings cleared')
 local stage=readString(r+0xb4d88,16)or '?'
 local all=B.actors(r);local c={ram=r,stage=stage,playerHealth=h.health,actors=all,bosses={}}
 for _,a in ipairs(all)do
  local p=catalog[a.name]
  if p and p.stages[stage]then
   local b={name=p.name,actor=a,phase='Not mapped',attackTimer='Not mapped',evidence='Not gameplay-validated'}
   local key=string.format('%X:%s:%X:%X',r,stage,a.offset,a.act)
   local signature=binary(r,psx(a.act),32)
   local cache=B.bindings[key]
   local changed=cache and cache.binding and binary(r,psx(cache.binding.callPC)-96,104)~=cache.callSignature
   if not cache or cache.signature~=signature or changed or not proof(r)then
    local binding,why=B.discoverBar(r,a);cache={binding=binding,why=why,signature=signature};B.bindings[key]=cache
    if binding then cache.callSignature=binary(r,psx(binding.callPC)-96,104)end
   end
   b.binding=cache.binding;b.reason=cache.why
   if b.binding then
    local raw=s32(r+a.offset+b.binding.offset);local now=raw*b.binding.scale
    if now&gt;=0 and now&lt;=b.binding.maximum then b.bar=now;b.maximum=b.binding.maximum;b.percent=100*now/b.maximum;b.raw=raw
    else b.reason='Resolved value outside health-bar range; reading suppressed'end
   end
   if a.name=='revolver.c'then B.ocelot(r,a,b)end
   if a.name=='wolf2.c'and c.stage=='s10a'then
    local ok,v=pcall(function()return dofile(dir..'int-boss-wolf.lua').health(r,a)end)
    if ok then
     b.hp=v.hp;b.maxHP=v.maximum;b.bar=(v.hp//8)*8;b.maximum=1024;b.percent=100*b.bar/1024
     b.phase='Hits remaining: '..v.hits..' / '..v.maximumHits;b.reason=nil
     b.evidence='First Integral Wolf half-health and defeat confirmed; independent health units and hit counter'
    end
   end
   if a.name=='psyco.c'then
    local ok,v=pcall(function()return dofile(dir..'int-boss-mantis.lua').health(r,a)end)
    if ok then
     b.hp=v.hp;b.maxHP=v.maximum;b.target=v.target;b.bar=v.hp;b.maximum=v.maximum;b.percent=100*v.hp/v.maximum
     b.phase='Mantis state '..v.phase..(v.visible and ''or ' | bar hidden')
     b.evidence='Integral Mantis-owned TARGET health, maximum and variable-scale renderer checked';b.reason=nil
    end
   end
   if a.name=='ninja.c'then
    local ok,v=pcall(function()return dofile(dir..'int-boss-ninja.lua').health(r,a)end)
    if ok then b.hp=v.hp;b.maxHP=v.maximum;b.phase='Ninja state '..v.phase;b.evidence=INTNinjaDefeat and INTNinjaDefeat.status or 'Integral Ninja health and phase-aware defeat confirmed in gameplay'end
   end
   if a.name=='m1e1.c'then
    local ok,v=pcall(function()return dofile(dir..'int-boss-tank.lua').health(r,a)end)
    if ok then
     b.hp=v.hp;b.maxHP=v.maximum;b.bar=v.bar;b.maximum=1024;b.percent=100*v.hp/v.maximum
     b.phase='Gunners remaining: '..v.remaining..' / '..v.total
     b.evidence='Integral native aggregate health mapped; tank defeat confirmed in gameplay'
     b.reason=nil
    end
   end
   -- CONTROL.mov is a signed SVECTOR. Coordinate layout is common to the
   -- validated Snake actor; Ocelot/tank include an extra field before CONTROL.
   local control=(a.name=='revolver.c'or a.name=='m1e1.c')and 0x24 or 0x20
   b.positionCandidate={}
   for j=0,2 do local v=assert(readSmallInteger(r+a.offset+control+j*2))&amp;0xffff;b.positionCandidate[j+1]=v&gt;=32768 and v-65536 or v end
   c.bosses[#c.bosses+1]=b
  end
 end
 return c
end
function B.capture(c,b)
 assert(B.captures&lt;8,'Eight-capture limit reached; start a new dashboard session for more')
 local a=b.actor;assert(u32(c.ram+a.offset+8)==a.act and u32(c.ram+a.offset+12)==a.die,'Boss actor changed')
 B.captures=B.captures+1
 local stem=dir..'../../logs/integral-boss-'..B.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'-'..B.captures
 local function write(suffix,data)local f=assert(io.open(stem..suffix,'wb'));local ok,err=f:write(data);f:close();assert(ok,err)end
 write('-actor.bin',binary(c.ram,a.offset,math.min(0x3000,0x200000-a.offset)))
 write('-overlay.bin',binary(c.ram,0xc0000,0xa0000))
 write('.txt',string.format('Read-only boss capture\nPID=%d\nStage=%s\nBoss=%s\nActor=%08X\nAct=%08X\nDie=%08X\nHealth=%s / %s\nEvidence=%s\nActor file is a bounded memory window, not an allocation-size claim.\n',B.pid,c.stage,b.name,0x80000000+a.offset,a.act,a.die,tostring(b.bar),tostring(b.maximum),b.evidence))
 B.lastCapture=stem;return stem
end
return B
]====]):sub(2),
 [ [====[Integral/int-boss-tank.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- Captured Integral tank director and gunner cross-actor health proof.
local T={}
local function u32(a)return assert(readInteger(a))&amp;0xFFFFFFFF end
local function check(r,a,kind)
 assert(a.act&gt;=0x800C0000 and a.act&lt;0x801F0000,'Tank code unavailable')
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Tank actor changed')
 local p=T.profiles[kind];assert(a.die==a.act+p.dieDelta,'Tank destructor differs')
 local bytes=assert(readBytes(r+(a.act&amp;0x1FFFFF),#p.bytes,true))
 for i=1,#p.bytes do assert(bytes[i]==p.bytes:byte(i),'Integral tank '..kind..' code differs')end
 return {address=r+(a.act&amp;0x1FFFFF),bytes=p.bytes}
end
function T.health(r,a)
 check(r,a,'director')
 local w=r+a.offset;local per,total,remaining,hp=u32(w+0xD74),u32(w+0xD70),u32(w+0xE08),u32(w+0xE0C)
 assert(per&gt;0 and per&lt;=32767 and total&gt;0 and total&lt;=16 and remaining&lt;=total and hp&lt;=per,'Tank health values differ')
 local combined=math.max(0,hp+per*(remaining-1));local maximum=per*total
 assert(combined&lt;=maximum,'Tank health calculation differs')
 return {hp=combined,maximum=maximum,bar=math.floor(combined*1024/maximum),gunnerHP=hp,gunnerMaximum=per,remaining=remaining,total=total}
end
function T.augment(r,a,e,actors)
 e.blocks[#e.blocks+1]=check(r,a,'director');e.conditions=e.conditions or {}
 for _,child in ipairs(actors)do
  if child.name=='m1e1sold.c'and u32(r+child.offset+0x1EC)==0x80000000+a.offset then
   e.blocks[#e.blocks+1]=check(r,child,'gunner')
   for _,v in ipairs({{8,child.act},{12,child.die},{0x1EC,0x80000000+a.offset}})do
    e.conditions[#e.conditions+1]={address=r+child.offset+v[1],size=4,value=v[2]}
   end
   -- Gunner loads director from +1EC, subtracts damage from director+E0C.
   -- The exact parent chain and RW instructions are in the retained block.
   local fn=child.act&amp;0x1FFFFF
   e.fields[0xE0C]={read={pc=0x80000000+fn+0x96C,word=0x8C820E0C},write={pc=0x80000000+fn+0x97C,word=0xAC820E0C}}
   return e
  end
 end
 error('No verified Integral tank gunner/director health link')
end
T.profiles={director={dieDelta=5052,bytes=('a8ffbd274c00b3af21988000500004245a000524213000005400bfaf5000b4af4800b2af4400b1afcde2000c4000b0af4c076326200062269000642600004d8c04004e8c08004f8c0c00588c00006dac04006eac08006fac0c0078ac10004224f6ff44141000632400004d8c04004e8c08004f8c00006dac04006eac08006facc8076326dc006226bc01642600004d8c04004e8c08004f8c0c00588c00006dac04006eac08006fac0c0078ac10004224f6ff441410006324dc0070262120000200004d8c0000000000006dac1c0102249fd2000c520162a620006426218800006c041424c00112246c0062969c0e63969e0e6596a00e6696211043006c0062a66e0062967000639621104500211866006e0062a69f96000c700063a6bdd2000c212000029fd2000c212072029fd2000c21207402e4009426010031260300222af8ff4014e40052262800a42723006d8a20006d9a27006e8a24006e9a2b00adab2800adbb2f00aeab2c00aebb2a00a297a40e63963000a527231043002a00a2a7280062969c0e639621880000231043003000a2a72a0062969e0e63966c041224231043003200a2a72c006296a00e6396c001102423104300236f000c3400a2a7bdd2000c21207002bdd2000c21207202e4005226010031260300222af8ff4014e4001026200064267669000c9c0065264007628e00000000070040147fff0424dc00628e000000002800438c0000000024186400280043ac400f628e00000000ffff422402004104400f62ae400f60ae440f628e00000000ffff422402004104440f62ae440f60ae480f628e00000000ffff422402004104480f62ae480f60ae4c0f628e00000000ffff4224020041044c0f62ae4c0f60ae500f628e00000000ffff422402004104500f62ae500f60ae540f628e00000000ffff422402004104540f62ae540f60ae580f628e00000000ffff422402004104580f62ae580f60ae600f628e00000000ffff422402004104600f62ae600f60ae640f628e00000000ffff422402004104640f62ae640f60ae5c0f628e00000000ffff4224020041045c0f62ae5c0f60ae680f628e00000000ffff422402004104680f62ae680f60ae6c0f628e00000000ffff4224020041046c0f62ae6c0f60ae700f628e00000000ffff422402004104700f62ae700f60ae740f628e00000000ffff422402004104740f62ae740f60ae780f628e00000000ffff422402004104780f62ae780f60ae800f628e00000000ffff422402004104800f62ae800f60aec00e638e010002240600621402000224c40e628ec80e60ae01004224aa530308c40e62ae180062148000033c0b80023c50ba428c00036334241043001200401400000000c80e628e0000000001004224c80e62ae03004228110040140c80023cae39020cc80e60ae030042300b00401020006426600e668ed0ca000c86000524ab5303080c80023cc00e638e03000224030062140c80023cc80e60ae0c80023c2c36428c00000000d00e428c000000000a0040140b80023c10ba438410ba4224440e63ae0200438400000000480e63ae04004284000000004c0e62ae20006386440e628e0000000023186200831803000014030003140200180042002800a3a722006386480e628e000000002318620083180300122800000014030003140200180042002a00a3a7240063864c0e628e000000002318620083180300122000000014030003140200180042002c00a3a72120a40012400000c249020c21208800801002005c0e62ae211840001f000224600e62ae411f6228030040103f000224f3530308600e62ae317562280c004010535f023c29394234c0e0632440190300180062003f000424c31f03001068000043130d002310430023208200600e64ae540d638e010002240c006214000000004007628e0000000008004014000000005c0e628ec40d638e000000002a1043000200401002000224540d62aeb00e628e000000001700401000000000f001438c010002241300621400000000080e628e00000000ffff42240a00401c080e62ae020004241e00052405000224540d62ae2110a000bd3e030c800f62ae1c54030800000000780d638e04000224540d62ae4c0f63ae080e628e000000000d00401c05000224540d638e000000000900621400000000800f628e000000000500401c000000007254000c2120600284570308000000004c0f628e000000002400401c04000224540d638e000000002200621401000224b00e628e000000001e00401401000224d00e628e000000001a00401401000224580d628e0000000010004014070002244f540308020002240b80043c10ba8424bd0005243f0006240b80073c50bae28c5a000324780f63ae00024234d0ca000c50bae2acb854030821880000540d62ae140e628e000000005c0f62ae540d638e010002242600621006000224250062109c0e6426080e628e740d638effff42241800620012200000700d628e00000000180062000c0e628e1218000021104400801202001a00430002006014000000000d000700ffff0124040061140080013c02004114000000000d0006001280000000000000020001060000000021800000100004241c000524bc0862261000a2afd80e668e5de3000c21380002d80e70ae9c0e642621280000a239020c08000624212060025f5e030ca40e60ae8f61030c212060029f58030c212060020b68030c212060028b69030c21206002d565030c2120600222006296a40e63962120600221104300506a030c220062a68503020c212060023c6b030c212060027274030c21206002d00e638e010002240200621400000000d00e60ae300e628e540d638ec00e60ae400760ae2c0e62ae06000224df02621000000000780f628e000000001600401c2188000021906002840a1024f7b5000c21207002aa0a4386a00d628e0000000090ff621448005226010031260a00222af6ff4014480010262188000021186002a00d629601003126aa0a62a40a00222afbff401448006324680e638e9c0d628e00000000238062001500000621880000240e628e000000001800500012180000280e628e000000001a00620002004014000000000d000700ffff0124040041140080013c02006114000000000d00060012100000900d638e0000000021884300780f628ef20871a63a0971a6860971a6ce0971a6160a71a66200401c5e0a71a66000201a000000006f006d8a6c006d9a73006e8a70006e9a2b00adab2800adbb2f00aeab2c00aebb2a00a287000000002118400000f8422808004010001062242a00a2a721184000001402000314020000f84228faff4014001062242a00a2870000000021184000010842280800401400f062242a00a2a721184000001402000314020001084228faff401000f06224340e648e3c0e658ec250020c000000002a00a3870000000023186200020061040000000023180300000463280700601000000000f7b5000ccc086426f7b5000c600964261d550308f0096426f7b5000c14096426f7b5000ca8096426380a6426f7b5000c00000000f208628600000000160051140b80043c3a096286000000001300511410ba842486096286000000000d00511400000000ce096286000000000900511400000000160a62860000000005005114000000005e0a6286000000000c005110000000000b80043c10ba8424bd0005243f0006240b80073c50bae28c5a000324780f63ae00024234d0ca000c50bae2ac4c0f628e00000000320040180f0042302c00401400000000dc00648e116f000ce00384242800a42721280000a239020c080006242800a42721288000926f000c010006243800b027212000022a00a297212800000cfe42242a00a2a72b00ad8b2800ad9b2f00ae8b2c00ae9b3300adab3000adbb3700aeab3400aebb3200a29708000624e8034224a239020c3200a2a70700042401000524213000002800a7273e0002243a00a2a73000a2271000a2af1400b0af1800a0af1c00a0af9134030c2000a0af4c0f628e000000008a00401c00000000500f628e000000008a00401c0f004230640d638e880d628e000000002a1043000700401421800000680d638e8c0d628e000000002a1043007a0040100000000021880002212860021807a38c0000000006006294000000000f004010212040002a1090000c004014000000004400628c00000000feff42240500422c0600401000000000780d628e21808000880e71ae43100200500f62ae010031260a00222ae9ff40140400a5245e000012000000007c0d628e000000001800500012400000840d638e000000001a00030102006014000000000d000700ffff0124040061140080013c02000115000000000d00060012180000800d628e000000001800500012400000840d648e000000001a00040102008014000000000d000700ffff0124040081140080013c02000115000000000d00060012200000640d628e880d658e23104300640d62ae680d628e640d638e23104400680d62ae2a10a3000200401000000000212860008c0d638e680d648e000000002a10640002004010640d65ae211880000b80043c9cb3842428006526236f000c680d63ae2800a42721280000a239020c08000624880e628e0000000005004228020040140004022400fc02242a00a2a7596f000c2800a4272800a42721280000a239020c080006242800a427212880000100062458020224926f000c2c00a2a7880e628e0000000080100200211062021807448c2800a527b3b9010c0800842420006426600e668ed0ca000cb1000524500f628e000000002c0040180f0042302b004014218800003800b027880e628e2120000280100200211062021807428c212800000b004d8808004d980f004e880c004e982b00adab2800adbb2f00aeab2c00aebb2b00ad8b2800ad9b2f00ae8b2c00ae9b3300adab3000adbb3700aeab3400aebb3200a29708000624e8034224a239020c3200a2a70700042402000524213000002800a7273e0002243a00a2a73000a2271000a2af1400b0af1800a0af1c00a0af9134030c2000a0af2188000010270424211860021807628c00000000260044a41807628c01003126280040a41807628c00000000060040a40a00222af5ff4014040063240b80023c9e4d428400000000420140100c80043c3436828c00000000ffff422404004104343682ac0c80023c303640ac343680ac540d638e07000224090062140c80053c0b80023cd0054394f0000224a200621402000224580d60ae84570308540d62ae3036a28c00000000090040140b80023cd0054394f000022405006214010002243036a2ac1e00022484570308343682ac0c80053c3436a28c00000000ffff42241d00422c1b0140100c80043c3036838c010002240b006214020002240b80023cd0054394050002240500621402000224303682ac1e000224f55603083436a2ac3036838c00000000050062140b80023cd00543940a00022467006210030002240c80043c3036838c0300022409006214040002240b80023cd00543940c0002240300621404000224e65603080c80033c3036838c00000000050062140b80023cd00543940010022453006210050002240c80043c3036838c0500022409006214060002240b80023cd0054394004002240300621406000224e65603080c80033c3036838c00000000050062140b80023cd0054294000000003f004310070002240c80043c3036838c0700022409006214080002240b80023cd0054394008002340300621408000224e65603080c80033c3036838c00000000050062140b80023cd0054394002002242b006210090002240c80043c3036838c09000224090062140a0002240b80023cd005439403000224030062140a000224e65603080c80033c3036838c00000000050062140b80023cd0054394e0000224170062100b0002240c80043c3036838c0b000224090062140c0002240b80023cd005439400100224030062140c000224e65603080c80033c3036838c000000000c0062140c80023c0b80023cd005439403000224070062140c80023c0d0002240c80033c303682ac1e000224f5560308343662ac3036438c0d000224080062140b80023cd0054394900002240400621401000224580d62ae07000224540d62ae540d638e070002248c0062140b80023cd005429400000000010042304400401055550a3c440e6296000000002800a2a7480e6296000000002a00a2a74c0e6396200342242a00a2a72c00a3a723006d8a20006d9a27006e8a24006e9a3300adab3000adbb3700aeab3400aebb3000a8872800a28756554a352340020118000a013200a9872a00a28710580000234822010000000018002a010b80043cec1984242800a5273000a627400107243400a3872c00a28710600000c34708002318620018006a002800a2972340680121104800c34f09003000a2a72a00a2972348890121104900c31f03003200a2a72c00a297105000002318430121104300b45c000c3400a2a70b80023c20ba428c000000000000458c0c80043c2800a28c01000324383683ac80004234505703082800a2ac0c80053c3836a38c010002240c0062140b80023c0b80023c20ba428c000000000000448c000000002800828c7fff03243836a0ac24104300280082ac0b80023cd005439400000000040062302f004010080062300400401000000000880f628e6157030832004224020062300500401000000000880f628e00000000ceff4224880f62aedc00648e116f000c700284242800a42721280000a239020c080006243000b0272120000221280000a239020c080006242800a42721288000e80302242c00a2a72a00a2a7d00702243400a2a7880f629601000624e8034224926f000c3200a2a72120000221280002926f000c010006240b80043cec1984242800a52721300002b45c000c400107245400bf8f5000b48f4c00b38f4800b28f4400b18f4000b08f0800e0035800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},gunner={dieDelta=3196,bytes=('b0ffbd274400b3af219880009007642621280000080006244c00bfaf4800b4af4000b2af3c00b1afa239020c3800b0afdc0070269fd2000c21200002200071269f96000c212020029307688a9007689a9707698a9407699a2b00a8ab2800a8bb2f00a9ab2c00a9bbbdd2000c21200002212020022b00a88b2800a89b2f00a98b2c00a99b930768aa900768ba970769aa940769ba7669000c9c006526e801628e00000000070040147fff0424dc00628e000000002800438c0000000024186400280043ac0c02628e00000000ffff4224020041040c0262ae0c0260ae1802628e00000000ffff422402004104180262ae180260ae1c02628e00000000ffff4224020041041c0262ae1c0260ae1c02628e000000001700401403000224ec01648e00000000d00e838c000000001100621400000000580d828c00000000020040140700022402000224540d82acec01638e01000224d00e62ac0b80023cf8016396984d42241c0043a4fc016396000000001e0043a43a0263860100022404006214f00160aef400628600000000000262aef400629600026396ea006486640060a6680060a623104300920762a60700822c360140100e80023c9c35422480180400211862000000628c000000000800400000000000ea006386020002242f00621401000224ec01648e00000000100e838c0000000028006214000000000b80023c984d5024100e80ac1600028600000000460040100b80023cd4b3428c00000000420040140b80043c10ba8424820005243f00062496000224180262ae3c000224d0ca000c1c0262aeec01628e03000324540d43acec01628e00000000d00e43ac1c00028600000000f80162ae1e00028600000000fc0162ae1e000296ffff0324fbff42240200422c280040141c0003a6917803081e0003a6ea006386000000002200621400000000ec01638e00000000100e628c000000001c004014000000001802628e000000001800401c00000000d40e628c000000001e0042281300401400000000ae39020c000000005555033c5655633418004300c3270200104000002320040140180400211864000700431020006426ec01638e96000224180262ae600e668cd0ca000c80000524ec01628e00000000dc00448c116f000c980484242800b027212000022128000201000624640002242800a0a72a00a0a72c00a0a73000a0a73200a0a7926f000c3400a2a73000a42721288000926f000c010006243000a5972800a297000000002328a2000014050003140200180042003400a4972c00a2970000000023208200123000000014040003140200180042002a00a3973200a2973000a5a73400a4a7231043003200a2a712600000c249020c2120cc003200a487c250020c21284000231002006c0062a63000a4873400a587c250020c00000000ec01638e6e0062a6700060a6dc00628c00000000ac044294000000002800a2a7ec01628e00000000dc00428c00000000b0044294000000002a00a2a7ec01628e00000000dc00428c00000000b4044294000000002c00a2a7ec01638ef400629622006394212000022110430038ff4224220062a62800a297200063962128000023104300640062a62c00a297240063960800062423104300a239020c680062a62120000221280002010006242c010224926f000c2a00a2a7c001648e40b5000c21280002212000020b80053c2a00a2979cb3a52496004224236f000c2a00a2a7764b020cc801642669790308000000000b80043c9cb38424236f000c280065262800a0a792076296000000002a00a2a79007628600000000180042001218000094076286000000001800420012600000c249020c21206c002800b027212000022128000201000624926f000c2c00a2a721206002220062862a00a68720006526067b030c21304600220062a62800a29700000000640062a62c00a29700000000680062a62300688a2000689a2700698a2400699a2b00a8ab2800a8bb2f00a9ab2c00a9bb4c00628e212800020800448cb1a5000c030006240100032403004310000000003f7903082a00a0a737a6000c2000a4272000a297000000002a00a2a7f401628e000000000e00401400000000220062862a00a38700000000231043002c0142280700401020006426ec01638e01000224f40162ae600e668cd0ca000c330005242a006286000000002c0262ae2a00a287000000006400422469790308300262ae0b80023c30b3428c0000000083100200010042300700401400000000dc00638e000000002800628c0000000080004234280062ac0c02628e000000001800401800000000f6006286000000002900401000000000ea006386000000000700622c240040100e80023cbc35422480180300211862000000628c000000000800400000000000dc006426212800002130a00035d3000c0500072495790308000000007254000c21206002dd7a030800000000dc0064260400052421300000050007243c00022435d3000c0c0262aef401628e000000000700401420006426ec01638e01000224f40162ae600e668cd0ca000c33000524c001628e00000000a40040100b80023cec01638e000000005c0f628c000000001a00401800000000d00e628c000000000d0040140b80023c30b3428c0000000083100200010042300700401400000000dc00638e000000002800628c0000000080004234280062acc001638e10270224260062a4c001628e00000000280040a4c001628e00000000060040a4c001668e000000008100c0100b80023cec01658e00000000740da48cec0da38c000000001a00830002006014000000000d000700ffff0124040061140080013c02008114000000000d000600121800000600c294000000002a1043001b00401000000000f00da28c000000001a00820002004014000000000d000700ffff0124040041140080013c02008114000000000d000600121000000c0ea38c000000002a10430009004014102702242600c2a4c001628e00000000280040a4c001628e00000000060040a4c001668e000000004f00c0100b80023c0600c294000000004b0040100b80023cec01658e00000000740da48cec0da38c000000001a00830002006014000000000d000700ffff0124040061140080013c02008114000000000d000600121800000600c294000000002a1043000400401400000000140ea28c1e7a03085c0fa2acf00da28c000000001a00820002004014000000000d000700ffff0124040041140080013c02008114000000000d00060012100000000000000600c2a4ec01638e00000000180e628c000000005c0f62acc001628eec01648e060043940c0e828c0000000023104300040041040c0e82acec01628e000000000c0e40acc001638e10270224260062a4c001628e00000000280040a4c001628e00000000060040a4ec01638e000000000c0e628c000000000400401820006426600e668cd0ca000c880005240b80023c984d43241600628400000000910040100b80023cd4b3428c000000008d00401400000000c001628e000000008900401000000000ec01628e000000000c0e428c000000008300401c000000009e00629400000000010042249e0062a4ec01638e00000000740d628c000000000c0e62acc001648e010002242cb5000cf00162ae200074262120800229b9010cc00160aeec01628e21208002600e468cd0ca000cb1000524dc007226fed2000c212040020e80043c335b000c8c3584240e80103c8435102621200002335b000c2188400021204002212820022d03062486d2000c213840002dd3000c21204002335b000c2120000221204002340265262130400084026726e80462261000a2af4c0762261400a2afc8076226c2d3000c1800a2af2120400211d3000c9c0065269fd2000c212040029f96000c21208002bdd2000c21204002ec01638e00000000080e628c00000000020042280400401421208002600e668c997a030881000524600e668c84000524d0ca000cdc00702621200002030005242130000035d3000c05000724212000022c026726060002242a00a2a70c0002242c00a2a70f0002242e00a2a7300262262800a0a71000a2af800002241400a2af1800a2af1c00a2af2a00a5972800a2972e00a697002c0500252845002c00a29700340600fe1f030c253046002800a4272128000008000624a239020c280262ae2000629600000000231002002800a2a72200629600000000231002002a00a2a72400629600000000231002002c00a2a76c0060a62800a4872c00a587c250020c000000006e0062a6700060a6040260aef4006286ec01638e000262ae2300688a2000689a2700698a2400699ab70e68a8b40e68b8bb0e69a8b80e69b8e80160ae4c00bf8f4800b48f4400b38f4000b28f3c00b18f3800b08f0800e0035000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
return T
]====]):sub(2),
 [ [====[Integral/int-boss-wolf.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
-- First Wolf encounter only. Source health-bar units and remaining hits
-- are independent; keep them consistent when changing health.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local M={pid=getOpenedProcessID()}
local function u16(a)return assert(readSmallInteger(a))&amp;0xFFFF end
local function u32(a)return assert(readInteger(a))&amp;0xFFFFFFFF end
function M.health(r,a)
 assert(a.name=='wolf2.c'and a.act==0x800D6C50 and a.die==0x800D78D4,'First Wolf native actor differs')
 assert(a.offset&gt;=0x10000 and a.offset+0xA74&lt;=0x200000,'Wolf bounds differ')
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Wolf changed')
 for _,p in ipairs(M.proofs)do
  local b=assert(readBytes(r+p.offset,#p.bytes,true));for i=1,#p.bytes do assert(b[i]==p.bytes:byte(i),'Integral Wolf native code differs')end
 end
 local e=dofile(dir..'int-ownership.lua').ownership(r,a)
 assert(e.targets[0x65C]and e.targets[0x660],'Wolf target ownership differs')
 local targets={}
 for _,o in ipairs({0x65C,0x660})do
  local p=u32(r+a.offset+o);assert(p&gt;=0x800B64E0 and p&lt;0x800B76E0 and (p-0x800B64E0)%0x48==0,'Wolf pool differs')
  assert(u16(r+(p&amp;0x1FFFFF)+2)==2,'Wolf target side differs');targets[#targets+1]=p
 end
 assert(targets[1]~=targets[2],'Wolf targets alias')
 local w=r+a.offset;local hp=u32(w+0xA40);if hp&gt;=0x80000000 then hp=hp-0x100000000 end
 local hits=u32(w+0x6FC);local maximumHits=u32(w+0x700);local step=u32(w+0xA48)
 assert(hp&gt;=-1024 and hp&lt;=1024 and maximumHits&gt;=1 and maximumHits&lt;=64 and hits&lt;=maximumHits,'Wolf health range differs')
 assert(step==math.floor(1024/maximumHits)+1,'Wolf native health step differs')
 return {hp=math.max(0,hp),rawHP=hp,maximum=1024,hits=hits,maximumHits=maximumHits,step=step,targets=targets,
 visible=u32(w+0xA0C)==2 and u32(w+0xA68)==0,finished=u32(w+0x9BC)==1,protected=u32(w+0x748)~=0 or u32(w+0xA54)~=0}
end
function M.augment(r,a,e)
 M.health(r,a)
 -- Exact native damage path: load hit count, decrement, store; then subtract
 -- per-hit units from the health bar. Retain all code for final plan checks.
 local function p(pc)return {pc=0x80000000+pc,word=u32(r+pc)}end
 e.fields[0x6FC]={read=p(0xDBA80),decrement=p(0xDBA90),write=p(0xDBA94)}
 e.fields[0xA40]={read=p(0xDBA98),write=p(0xDBAA4)}
 e.blocks=e.blocks or {}
 for _,b in ipairs(M.proofs)do e.blocks[#e.blocks+1]={address=r+b.offset,bytes=b.bytes}end
 return e
end
function M.setHealth(hp)
 assert(getOpenedProcessID()==M.pid,'Attached process changed')
 local G=dofile(dir..'int-inventory.lua');local safe=G.context(true)
 local B=dofile(dir..'int-boss-observer.lua');local c=B.inspect()
 assert(c.ram==safe.ram and c.stage=='s10a'and #c.bosses==1,'Enter first Wolf combat')
 local a=c.bosses[1].actor;local r=c.ram;local h=M.health(r,a)
 assert(type(hp)=='number'and hp%1==0 and hp&gt;0 and hp&lt;=1024,'Invalid Wolf health')
 assert(h.rawHP&gt;0 and h.hits&gt;0 and h.visible and not h.finished and not h.protected,'Wait for active vulnerable Wolf')
 assert(u16(r+0xBD360+0x2A)==0,'Close the menu')
 for _,p in ipairs(h.targets)do assert(u16(r+(p&amp;0x1FFFFF)+6)&amp;4==0,'Wolf is processing a hit')end
 local fresh=G.context(true);assert(fresh.ram==r and fresh.stage=='s10a'and getOpenedProcessID()==M.pid,'Encounter changed')
 local now=M.health(r,a);assert(now.rawHP==h.rawHP and now.hits==h.hits and now.visible and not now.finished and not now.protected,'Wolf state changed')
 for i,p in ipairs(h.targets)do assert(now.targets[i]==p and u16(r+(p&amp;0x1FFFFF)+6)&amp;4==0,'Wolf target changed')end
 local hits=math.min(h.maximumHits,math.ceil(hp/h.step))
 assert(writeInteger(r+a.offset+0x6FC,hits),'Wolf hit-counter write failed')
 assert(writeInteger(r+a.offset+0xA40,hp),'Wolf health write failed')
 return {beforeHP=h.rawHP,hp=hp,maximum=1024,beforeHits=h.hits,hits=hits,work=a.offset}
end
function M.equipRifleForRetreat()
 -- Narrow recovery for the proven Wolf retreat branch. The general inventory
 -- controller retains its normal restricted-scene refusal.
 assert(getOpenedProcessID()==M.pid,'Attached process changed')
 local G=dofile(dir..'int-inventory.lua');local c=G.context(false);local r=c.ram
 local B=dofile(dir..'int-boss-observer.lua');local b=B.inspect()
 assert(c.stage=='s10a'and b.ram==r and #b.bosses==1,'Enter first Wolf encounter')
 local a=b.bosses[1].actor;local h=M.health(r,a)
 local function check()
  assert(getOpenedProcessID()==M.pid and G.context(false).ram==r,'Process or RAM changed')
  local flags=u32(r+0xAB3CC);local status=u32(r+0xABA50)
  assert(flags&amp;0x10000000~=0 and flags&amp;0xC40C0000==0 and status&amp;0x20002084==0 and u32(r+0xAB3D4)==0 and c.h.health&gt;0,'Not the normal Wolf retreat restriction')
  assert(u32(r+0xBD360+8)==0x800386A4 and u32(r+0xBD360+12)==0x800387E8 and u16(r+0xBD360+0x2A)==0,'Close the menu')
  local h=M.health(r,a);assert(h.visible and not h.finished and h.hits&gt;0 and u32(r+a.offset+0x718)==1,'Wolf retreat branch is not active')
  local z=u16(r+0xABA14);if z&gt;=32768 then z=z-65536 end
  assert(z&lt;u32(r+a.offset+0x9D0)and u16(r+0xB4DB4)~=9,'Wolf retreat condition changed')
  G.reader.checkFeature('inventory')
 end
 check();local stock=r+0xB4DBA+18;local capacity=r+0xB4DCE+18
 local previousStock=u16(stock);local previousCapacity=u16(capacity)
 local amount=previousStock==0xFFFF and 20 or math.max(previousStock&amp;0x7FFF,20)
 local cap=previousCapacity&gt;=32768 and 0 or previousCapacity
 check();assert(u16(stock)==previousStock and u16(capacity)==previousCapacity,'Inventory changed')
 if cap&lt;amount then assert(writeSmallInteger(capacity,amount))end
 assert(writeSmallInteger(stock,amount));G.equip('weapon',9,c)
 return {stock=amount,requestedWeapon=9}
end
M.proofs={{offset=0xD6950,bytes=('d8ffbd272000b2af219080002400bfaf1c00b1af1800b0af680a428e000000002a00401400000000400a428e00000000020041040000000007004224c3100200c0800200020001060000000021800000440a518e213800022a10300203004010213020022130000221880002bc09438e010002240a006214340a42260800301600000000500a438e000000001e0062280e00401001006224500a42ae340a42261000a2af100004245de3000c1c0005242a1011020500401000000000440a428e00000000f8ff4224440a42ae2400bf8f2000b28f1c00b18f1800b08f0800e0032800bd27400a828c00000000020041040000000007004224c3100200c0100200440a82ac0e80023c0e80033cbc406824104b47240300058900000599040006810300e5a80000e5b80400e6a0104b4224340a8324340a82ac10000224040062a06f000224050062a09f000224060062a01f000224070062a0df000224080062a07f0002240800e003090062a0'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0xD6C50,bytes=('0b80023cd4b3428cd8ffbd271c00b1af218880002400bfaf2000b2af070040101800b0af580a228e000000000e0040140100022459df000c580a22ae580a228e00000000080040140000000036df000c0000000001000324030043140000000059df000c000000000c0a228e020010240300501400000000545a030c212020020c0a238e0100022406006214000000000c0a30ae8d5a030c21202002545a030c21202002680a228e000000000700401069100224240022a682be0224280022a6000802242e0022a6720022a69c09228e000000000200401424003026480000a69f96000c21200002e2d2000ca0002426e2d2000c840124260b80023cb64d43840600022408006214fffe0424a000238e000000002800628c0000000000014234645b0308280062aca000228e000000002800438c0000000024186400280043ac212000027669000c1c0625260b80023c30b3428c000000003f0042300500401400000000245c000c0200042401004224d80722ae5007258edc07308ed807228e4c07238e21800202dc0730ae4000648c095a030c213000024c07228e5007258e4400448c095a030c21300002a000228e00000000e60142840000000003004104038102000f004224038102000300001e0001022a010010240001022a0200401400000000ff001024e007228e000000004000448cee59030c21280002e007228e000000004400448cee59030c21280002280a238e010002241a0062140b80023cae4d428400000000160040100b80023cd4b3428c0000000012004014212020020b80053cccb3a28c0010033c25104300af5a030cccb3a2ac0b80023c2400238610ba4284000000002a104300030040100b80033cb45b0308002002240080023458b962a4bc09308e0100022455000216000000009c09228e00000000290040100b80123c10ba4226040042840000000050c942282400401024002426280a228e00000000200040140b80023c984d4624ffff07240b80053cccb3a28c1e00c3944a00043c1c00c7a425104400feff63240300632c02006014ccb3a2ac1e00c7a43577043c00948434b187030c2128000024002386300a22ae280a30ae10ba4286000000002a10430004004010ffff0224d80930aee55b0308dc0930aed80922aedc0922ae240024260b80103ca15b000c10ba0526d409238e000000002a10430013004014ffff0224dc09248e0000000007008214010002242400238610ba0286000000002a1043000900401401000224170082140b80023c2400238610ba0286000000002a104300110040140b80023cffef053cffffa5340b80033cccb3628c300a248e24104500d787030cccb362ac212020027254000c300a20ae105c03080b80023c205f030c212020020b80023c30b3428c000000007f0042303100401400000000a000248e8610030c70028424fc06228e000000002a00401c0a80023c6cf4438c01000224260062140b80023ce00542940000000010004230210040105555043c0a80073c2400268678f4e284565584342330c2001800c40078f4e8241200a0a7c337060010480000233026011000a6a72800238604000285000000002318620018006400840005241000a427c31f030078f4e29402000795211046001000a2a71200a7a7040002951048000023182301211043001400a3a716ca000c1400a2a72400bf8f2000b28f1c00b18f1800b08f0800e0032800bd27b0ffbd273c00b3af219880004400b5af240075262120a0023400b1af01001124e80302244800bfaf4000b4af3800b2af3000b0afd80771aedc0760ae6796000cd40762ae980140042120a0028f98000c050005242120a002ffff05242130a0008b98000c2138a0002120a0029198000c040005245a82000c750004242180400005000012000000007a82000c21200002725c0308fc0762aefc0771ae5a82000c70000424218040001000001200000000fc07628e0000000020004018218800008808122421200002475a030c21287202fc07628e010031262a102202f9ff4014080052269a5c030800000000fc07628e0000000011004018218800000b80043c211860029cb38b24030068890000689907006989040069998b0868a8880868b88f0869a88c0869b8fc07628e010031262a102202f3ff4014080063245a82000c6d0004241500401000000000fc07628e000000001c0040182188000021906002a982000c000000002180400004000012000000007a82000c21200002000842aefc07628e010031262a102202f4ff401404005226be5c03080400023cfc07628e00000000080040182188000021186002000860acfc07628e010031262a102202fbff4014040063240400023ce09342346800042405001124240762ae5a82000ce00671ae2180400005000012000000007a82000c21200002cc5c0308000762ae000771ae0007628e0000000021184000fc0662aeffff02240300621401000224d65c0308680a62ae680a60ae6c0a60ae6b000424a00072265a82000c840174262180400005000012000000007a82000c21200002e35c03089c0962ae9c0960ae9c09628e00000000060040140e80103cc4401026335b000c21200002f05c0308000000000e80043c335b000ccc4084240e80043c0e80043cc4408424335b000c2180400021204002212800022d02062486d2000c213840005a82000c6f0004242180400005000012624302247a82000c21200002035d0308d00962aed00962ae5a82000c630004242180400007000012ffff02247a82000c21200002c00962ae01000224105d0308c40962aec00962aec40960ae5a82000c6a0004242180400005000012ffff02247a82000c212000021a5d0308e40962aee40962ae5a82000c72000424218040001f00001221200002325a030c2000a5272a00a2870000000018004014000000002300a88b2000a89b2700a98b2400a99b270068aa240068ba2b0069aa280069ba2c0060a62800a297300060a62e0062a6010002242f00688a2c00689a3300698a3000699a730068aa700068ba770069aa740069ba3d5d0308bc0962aefc0662ae0007638e000402241a00430002006014000000000d000700ffff0124040061140080013c02004114000000000d0006001210000064000424ffff1124c80971ae010042245a82000c480a62ae2180400005000012000000007a82000c21200002585d0308c80962aec80971ae5a82000c690004242180400005000012ffff02247a82000c21200002625d0308e00962aee00962ae5a82000c650004242180400005000012ffff02247a82000c212000026c5d03084c0a62ae4c0a62ae5a82000c670004242180400005000012881302247a82000c21200002765d0308d40962aed40962ae5a82000c710004242180400005000012000000007a82000c21200002805d0308e80962aee80960ae2dd3000c212040020e80043c335b000cc4408424212040026802652621304000b80267261c0562261000a0af1400b5afc2d3000c1800a2af212040021c06702611d3000c212800020e80043c335b000cd840842421208002212840006d00062486d2000c213800002120800211d3000c21280002212080022128400217d3000c04000624185f030c2120600215000424080005242130000054076726af6e000c1000a0af2180400007000012000000009d60000c212000020b80023cb0b9428c00000000280002a6420000124c0770ae0e80043ce0408424d0070224335b000c2e0002a60c76000c212040002190400038004012500772ae212840024000048e1e5a030c100011244400048e1e5a030c2128400229ff04242000032480006226540740a4560744a4580743a4ffff3126fbff201ef8ff4224090404240200052421300000e40767264c07638e080002242a0062a40c80023c2c374224af6e000c1000a2af2180400007000012000000009d60000c212000020b80023cb0b9428c00000000280002a612000012e00770ae4000048ef659030c000000004400048ef659030c0000000030000424640002242e0002a62400028efffe0324241043008358000c240002ae2120400003008014200064ae2c5e0308ffff022400e1033c2002633401000224030082a00b0082a003000224130082a062000224170082a060ff0224180082a490ff02241a0082a4400102241c0082a4e00002241e0082a40b80023c040083ac0c0083ac1000888c1400898c18008a8c1c008b8c200088ac240089ac28008aac2c008bac140080a0150080a0160080a0240080a0250080a0260080a09cb34b2403006889000068990700698904006999130a68aa100a68ba170a69aa140a69ba680a628e0000000006004010ffff0224c00962aee40962aec80962ae4c0a62aee00962ae211000004800bf8f4400b58f4000b48f3c00b38f3800b28f3400b18f3000b08f0800e0035000bd27e0ffbd271400b1af21888000ffef053cffffa5340b80033cccb3628c240024261800bfaf1000b0af241045003398000cccb362acfed2000ca0002426fed2000c840124265c06248e2cb5000c000000006006248e2cb5000c000000004c07308e000000000500001200000000b860000c21200002016f000c21200002e007308e000000000500001200000000b860000c21200002016f000c212000022000248e0000000003008010000000009558000c00000000bc09238e010002240900621400000000c409228e000000000500431400000000ba59030c21202002745e030800000000e409238effff02240300621000000000d359030c212020021800bf8f1400b18f1000b08f0800e0032000bd27d8ffbd271c00b1af21888000fa000324e80302242000bfaf1800b0af1000a3a71200a2a700b5000c1400a3a7218040001a0000125c0630ae2120000210000524020006241db7000c2138a50300000296000000000002423400b5000c000002a6218040000d000012600630ae2120000210000524020006241db7000c2138a503000003962110000000026334000003a600040324a15e0308400a23aeffff02242000bf8f1c00b18f1800b08f0800e0032800bd27d8ffbd271800b2af219080001c00b3af2198a0002000b4af21a0c0002400bfaf1400b1afec2e020c1000b0af2118400003006104038a0200ff006224038a020000121100238862000700201a21800000245c000c00100424010010262a101102fbff401400000000212040022128600221308002ac0980a4ae0980a4b00980a4f00980ac4b5c030c580a80ac2118400002006004ffff0224211000002400bf8f2000b48f1c00b38f1800b28f1400b18f1000b08f0800e003'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0xDAE00,bytes=('4000bd2780ffbd277800b4af21a080007c00bfaf7400b3af7000b2af6c00b1af6800b0af5c0a838e640a80ae4010030021104300c010020023104300a000838e801002002118620048006a8c4c006b8c50006c8c54006d8c2800aaaf2c00abaf3000acaf3400adaf58006a8c5c006b8c60006c8c64006d8c3800aaaf3c00abaf4000acaf4400adaf600a838e000000004010030021104300c010020023104300a000838e801002002118620048006a8c4c006b8c50006c8c54006d8c4800aaaf4c00abaf5000acaf5400adaf58006a8c5c006b8c60006c8c64006d8c5800aaaf5c00abaf6000acaf6400adaf5c06918e9c09828e6006928e120040140b80023cb44d4384030002240e006214000000000000229600000000eaff423001004234000022a60000429600000000eaff423001004234000042a65a000224e06b0308540a82ae540a828e0000000003004018ffff4224e06b0308540a82ae540a80ae000022960000000015004234000022a6000042960000000015004234000042a69c09828e0000000005004010ffff0224c809838e00000000080062140b80103cffef043c0b80033cccb3628cffff843424104400ccb362ac0b80103cccb3028eec06838e0001423403006018ccb302aeffff6224ec0682aec809838effff02248b00621002000224cc09838e000000001e00621403006228f009828e01000324070043100000000048a6010cf00983aeccb3028e4a00033c25104300ccb302aecc6a030c212080020b80023c50ba428c8000033c24104300070040100b80023cb64d429400000000feff42240300422c030040100000000003000224cc0982aecc09838e0000000003006228450040140100622421208002cc6a030ccc0982ae0b80043c58b9822458b980a4020040a4cc09838e280002240800621046000224040062145500022400100224616c030858b982a4040062147700022440000224616c030858b982a40700621495000224212000003f0005245aca000c10000624616c0308000000001b00621496006228240a838e0900022403006210040002240400621400000000240a83960b80023cb44d43a4200a838e01000224070062100c00022405006210050002240300621006000224050062140b80033c200a83960b80023cb64d43a40b80033c0c000224616c030858b962a40a004014ffbf053cffffa5340b80033cccb3628c2120800224104500b76a030cccb362ac7254000c21208002cc09838e01000224200062140b80023cae4d4284000000001c0040100b80023cd4b3428c00000000190040148888033c02000224cc0982ae0b80023c58b940a458b942240b80043c0040053c0b80033c020040a4ccb3828c10ba638425104500c832632803006010ccb382ac7f6c0308281d0224d8d60224180a82a6401f02241a0a82a650c902241c0a82a68888033c0b80023c30b3448c8988633418008300c31704001050000021184401c31803002318620000110300231043002d00821421208002245c000c0200042429004014212080020b80023c20ba438c000000000000628c00000000cc01429400000000fc0982a60000628c00000000d001429400000000fe0982a60000628ce809838ed401429400000000000a82a60200022414006214000000007864030c212080020e00401001000224040a82ae0e80023c304b4a2403004b8900004b9907004c8904004c99ff098baafc098bba030a8caa000a8cbabe6c030821208002040a80ae21208002c865030c24008526fc06838e0000000062006018d80682ae0b80023c14ba4284d009838e000000002a1043005b0040100b80023c50ba428c8000033c2410430027100200550040100b80023c984d45241c00a3840900022450006210000000001600a284000000004c0040100b80023cd4b3428c00000000480040140b80043cccb3828c0010033c251043001e00a384ccb382ac01000224070062100c00022405006210050002240300621006000224050062140b80023c0b80033cffff0224b64d62a40b80023c984d44241c0083840900022403006210040002240300621400000000ffff02241c0082a401000424180784aee80680ae93098b8a90098b9a97098c8a94098c9a2f008baa2c008bba33008caa30008cba5c06838e000000000600629400000000fbff4230060062a46006838e000000000600629400000000fbff4230060062a4080a828e000000000200401400000000080a84aec809838effff02240500621000000000700a828e000000000300401400000000a864030c21208002080a838e010002248000621402000224a26d0308080a82ae680a828e0100102405005014000000006c0a828e000000007600401000000000c809838effff02244000621021202002e007838e000000002400628c0000000000014234240062ac4c07838e000000002400628c0000000000014234240062ac000022960000000000024234000022a6000042960000000000024234000042a6060022960000000004004234060022a6060042962000a5270400423440b5000c060042a62120400240b5000c2000a5273c00a297ac0683960000000021104300080022a64000a297ae06839600000000211043000a0022a64400a297b006839600000000211043000c0022a65c00a297b40683960000000021104300080042a66000a297b606839600000000211043000a0042a66400a297b806839600000000211043004d6f03080c0042a6cc06828e0000000005004010180780ae07005010000000007e6d0308000000003266030c212080027e6d0308cc0690aeab6a030c21208002fc06828e000000001c00401cf0d802242000a0a72200a2a72400a0a7000022962120200200024234000082a4000042962000a5270002423440b5000c000042a62120400240b5000c2000a5270b80023c9cb34a2403004b8900004b9907004c8904004c99130a8baa100a8bba170a8caa140a8cba4d6f030800000000e806858e1007868e1407878ef35f030c212080028360030c212080020b80023cb44d4384090002246f0062140b80023c100a8286000000002a004018ff00093cffff29350b80033c0b80023cec19632400ff083c20b9478c2000848e8010070021104300002907002120a4001000a5240000468c1000838c0000c28c241868002410490025186200100083ac0000c38c2000828e241868002110450024104900251862000000c3ac2000848ec03807002120e4000000828c241869002410480025104300000082ac0000c38c2000828e241868002110470024104900251862000000c3ac0b80053c20b9a28c2000838e100a84920011020021104300140044a020b9a28c2000838e120a84920011020021104300150044a020b9a28c2000838e140a84920011020021104300160044a0100a8286100a8396020041040000000007004224c3100200120a8486120a85962310620002008104100a82a607008424c3100400140a8386140a84962310a20002006104120a82a607006324c3100300100a839623108200140a82a6ffff6324ffff62301f00422c0200401000000000100a83a6120a829600000000ffff4324ffff62301f00422c0200401000000000120a83a6140a829600000000ffff4324ffff62301f00422c0d0040100b80023c216e0308140a83a69cb34a2403004b8900004b9907004c8904004c99130a8baa100a8bba170a8caa140a8cba0b80023cb44d4384040002241100621421202002f0d802242000a0a72200a2a72400a0a7000022960000000000024234000022a6000042962000a5270002423440b5000c000042a621204002556e03082000a5270000229600000000fffd4230000022a60000429600000000fffd4230000042a6a000828e000000005c004294000000002000a2a7a000828eae0683966000429400000000211043002200a2a7a000828e00000000640042942000a52740b5000c2400a2a721204002a000828eb6068396600042942000a527211043002200a2a740b5000c000000003c00a297ac0683960000000021104300080022a64000a297ae06839600000000211043000a0022a64400a297b006839600000000211043000c0022a65c00a297b40683960000000021104300080042a66000a297b606839600000000211043000a0042a66400a297b806839600000000211043000c0042a6060022960000000004004230060040140000000006004296000000000400423009004010000000004807828e000000000500401400000000540a828e000000000900401001000224680a838e01000224b6006214000000006c0a828e00000000b2004014010002246c0a82ae3c0002242c0a82aef80980ae06002296000000000400423003004010212080029b6e0308060005240e0005242c64030c020006249c058426e15f030c10000524fc06828e01000324480783ae480a838effff4224fc0682ae400a828ed406848e23104300400a82ae1100822c260040100e80023cb041422480180400211862000000628c000000000800400000000000fc06828e000000000c00401c0c0002240b80023cd4b3428c0000000004004014000000000001043c51b9000c01008434e007838ede6e03080d000224d40682ae245c000c0200042406004010212000001f0005245aca000c80000624ff6e0308000000001f0005245aca000c81000624ff6e030800000000fc06828e000000001d00401c0b80023cd4b3428c00000000030040140001043c51b9000c01008434e007838e09000224d40682ae2400628c0000000000014234240062ac4c07838e000000002400628c0000000000014234240062ac680a828e0000000013004014212000001f0005245aca000c82000624ff6e030800000000245c000c0200042404004010212000001f000524fb6e0308800006241f000524810006245aca000c0000000008000224d40682aefc06828e000000003e00401c000000009c09828e000000003a004010a0009226fed2000c2120400284019326fed2000c212060020e80043c335b000c944184240e80103ca041102621200002335b000c2188400021204002212820022d02062486d2000c213840002dd3000c21204002335b000c21200002212040026802852621304000b8028726240082261400a2af1c0582261000a0afc2d3000c1800a2af212040021c06902611d3000c212800020e80043c335b000ca841842421206002212840006d00062486d2000c213800002120600211d3000c21280002212060022128400217d3000c040006248401838e000000002800628c0000000080004234280062acb565030c21208002f006828e00000000ffff4224f00682aef806828e2c0a838e0100422403006018f80682aeffff62242c0a82ae7c00bf8f7800b48f7400b38f7000b28f6c00b18f6800b08f0800e003'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
return M
]====]):sub(2),
 [ [====[Integral/int-boss.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Ocelot only. Native code and actor ownership must match before any action.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader or dofile(dir..'int-reader.lua')
local D=dofile(dir..'int-discovery.lua')
local G=dofile(dir..'int-inventory.lua')
local B={pid=R.pid,version=1}
local function u16(a)return assert(readSmallInteger(a))&amp;0xFFFF end
local function u32(a)return assert(readInteger(a))&amp;0xFFFFFFFF end
local function proof(r,fn)
 -- Generated exact blocks include damage notification, mode dispatch, HP to
 -- health-bar scaling, and normal defeat state/counter/bar assignments.
 for _,p in ipairs(B.proofs)do
  local bytes=assert(readBytes(r+(fn+p.delta),#p.bytes,true))
  for i=1,#p.bytes do assert(bytes[i]==p.bytes:byte(i),'Integral Ocelot code differs')end
 end
end
function B.inspect(writing)
 local c=G.context(writing);local r=c.ram
 assert(c.stage=='s04b','Enter the Integral Ocelot encounter')
 local root=D.actorRoot(r);local boss
 for level=0,8 do
  local start=root+level*0x44;local finish=start+0x20
  local previous=start;local p=u32(r+start+4);local seen={}
  for n=1,512 do
   assert(p&gt;=0x80000000 and p+32&lt;=0x80200000,'Actor pointer invalid')
   local w=p&amp;0x1FFFFF
   if w==finish then assert(u32(r+w)==0x80000000+previous,'Actor tail changed');break end
   assert(not seen[w]and u32(r+w)==0x80000000+previous,'Actor list changed');seen[w]=true
   local np=u32(r+w+20)
   if np&gt;=0x80000000 and np+48&lt;=0x80200000 and readString(r+(np&amp;0x1FFFFF),48)=='revolver.c'then
    assert(not boss,'Multiple Ocelot actors');boss={work=w,act=u32(r+w+8),die=u32(r+w+12)}
   end
   previous=w;p=u32(r+w+4);assert(n&lt;512,'Actor limit')
  end
 end
 local b=assert(boss,'Ocelot actor is not loaded')
 assert(b.act&gt;=0x800C0000 and b.act&lt;0x801F0000,'Ocelot Act invalid')
 local fn=b.act&amp;0x1FFFFF;proof(r,fn)
 assert(b.die==b.act+0x398,'Ocelot destructor differs')
 b.target=u32(r+b.work+0x83C);local t=b.target&amp;0x1FFFFF
 assert(b.target&gt;=0x800B64E0 and b.target&lt;0x800B76E0 and (b.target-0x800B64E0)%0x48==0,'Ocelot TARGET pool differs')
 b.hp=u16(r+t+0x26);b.maximum=u32(r+b.work+0x960);b.bar=u32(r+b.work+0x854)
 b.phase=u32(r+b.work+0x8FC);b.counter=u32(r+b.work+0x900)
 assert(b.maximum&gt;0 and b.maximum&lt;=32767 and b.hp&lt;=b.maximum and b.bar&lt;=1024 and b.phase&lt;=6,'Ocelot state out of range')
 assert(math.abs(math.floor(b.hp*1024/b.maximum)-b.bar)&lt;=8,'Ocelot health bar is updating; retry')
 b.ram=r;b.stage=c.stage;b.pid=R.pid
 return b
end
function B.setHealth(value)
 assert(type(value)=='number'and value%1==0 and value&gt;=0,'Invalid HP')
 local b=B.inspect(true);local r,w,t=b.ram,b.work,b.target&amp;0x1FFFFF
 assert(value&lt;=b.maximum and b.hp&gt;0 and b.phase~=4 and b.phase~=6,'Wait for active combat')
 assert(u32(r+0xBD360+8)==0x800386A4 and u32(r+0xBD360+12)==0x800387E8 and u16(r+0xBD360+0x2A)==0,'Close the menu')
 local flags=u16(r+t+6);assert(flags&amp;4==0,'Ocelot is processing a hit; retry')
 -- Revalidate the live binding before publishing a native damage event.
 local c=G.context(true)
 assert(c.ram==r and c.stage==b.stage and getOpenedProcessID()==B.pid,'Game changed')
 proof(r,b.act&amp;0x1FFFFF)
 assert(u32(r+w+8)==b.act and u32(r+w+12)==b.die and u32(r+w+0x83C)==b.target and u16(r+t+0x26)==b.hp and u16(r+t+6)==flags,'Boss changed; retry')
 assert(writeSmallInteger(r+t+0x3E,0),'Mode write failed')
 assert(writeSmallInteger(r+t+0x26,value),'HP write failed')
 assert(writeSmallInteger(r+t+6,flags|4),'Damage notification failed')
 B.last={stage=b.stage,work=w,target=b.target,beforeHP=b.hp,requestedHP=value}
 return B.last
end
function B.defeat()return B.setHealth(0)end
B.proofs={{delta=-8052,bytes=('e0ffbd271400b1af218880001800bfaf1000b0af3c08308e0000000006000396000000000400623076004010fbff6230060002a6010002247b47030c940822ae3e000386030002240d0062102400242604006228050040100200022414006210212020022d4d0308020005240400022407006210212020022d4d03080200052426000296340005240f4d0308ffff4224240024262600029635000524fdff422416ca000c260002a6304d03080b80023c4400038e0600022417006214020005245408238e6009228e0000000018006200121000000300410483220200ff034224832202005555033c2600028656556334231082004010020018004300c3170200103800002310e20023208200260004a62120200202000524cb4c030c213000000b80023cd4b3428c0000000008004010000000003c08238e0000000026006284000000000200401c01000224260062a43c08228e00000000260044846009238e801204001a00430002006014000000000d000700ffff0124040061140080013c02004114000000000d000600121000000a008018540822ae124c030c212020023c08238e212000000000629489000524ebff42305e4d0308000062a42120200204000224fc0822ae124c030c000920ae2120000088000524540820ae16ca000c000000002700278a2400279a2b00288a2800289a6b0827aa680827ba6f0828aa6c0828ba1800bf8f1400b18f1000b08f0800e0032000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=0,bytes=('d8ffbd271c00b1af218880000b80023c0e80033c10ba449410ba42242000bfaf1800b0af70fe64a40b80043c04004294f4b9848c70fe6324040062a40200829400000000020062a4b00023860e0002242400621400000000a2012286000000000700401400000000e6062296ca0123960008422400086324e60622a6ca0123a6bc0022860000000016004010000000008808228e000000001100401003000224b400238eb00022a604000224400062ac8008228e000000000a0040100100033c01f86334feff023cfe074234a80122ae01000224900123aefd5403089c0122a6b00020a69fd2000ca0002426b8002396e0ff02246a0022a6560023a6b0002386030002241e006214000000008808228e000000001a0040100b80023c9a4d428400000000020040042120000021204000680023868010040021104400c01002000001442418006400121800000200610400000000ff0063246c0022860000000018004400031203001220000002008104680022a6ff008424031204006c0022a69f96000c240024262400248628002586a94d030c0000000021184000030060100700022408006214fdff62242800228600000000602242280200401060220224280022a6fdff62240200422c09004010ffff62242800228600000000810c422804004014ffff6224800c0224280022a6ffff62240200422c08004010fbff622424002286000000002c014228020040102c010224240022a6fbff62240200422c070040100000000024002286000000004deb4228020040144ceb0224240022a6bdd2000ca000242624003026212000027669000cfc0725263c08248e40b5000c212800023c08248e85b6000c000000001454030c21202002b04c030c212020022654030c212020021c000424440822261000a2af5008258e5408268e78e3000c000407245408238e5008228e00000000030062140a0002247e550308580822ae5808228e00000000ffff422406004104580822ae5008248e5408258e1b99000c40000624500822aee056030c212020020b80033c10ba6294000000006f174224ffff4230571b422c1a00401010ba63240400638400000000c5096228150040141c256228130040100000000024002286240024963df64228030040140b80033c9755030818fc8224e80382245c7762a4280022862800249671174228030040140b80033ca055030818fc8224e8038224607762a45454030c212020028954030c212020022000bf8f1c00b18f1800b08f0800e0032800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{delta=984,bytes=('3c08048e2cb5000c00000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
INTBoss=B
return B
]====]):sub(2),
 [ [====[Integral/int-discovery.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Read-only discovery of resident actor lists and relocated overlay parameters.
local D={version=1,root=nil}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xffffffff end
local function offset(p,n)
 assert(p and p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'Invalid PSX pointer')
 return p&amp;0x1fffff
end
local function header(ram,o)
 local b=assert(readBytes(ram+o,32,true),'Actor header unavailable')
 assert(#b==32,'Short actor header')
 local function w(i)return b[i+1]|(b[i+2]&lt;&lt;8)|(b[i+3]&lt;&lt;16)|(b[i+4]&lt;&lt;24)end
 return {offset=o,prev=w(0),next=w(4),act=w(8),die=w(12),namePointer=w(20)}
end
local function rootsValid(ram,root)
 if not root or root&lt;0x10000 or root+9*0x44&gt;0x200000 then return false end
 for i=0,8 do
  local s=header(ram,root+i*0x44);local e=header(ram,root+i*0x44+0x20)
  if s.prev~=0 or s.act~=0 or s.die~=0 or e.next~=0 or e.act~=0 or e.die~=0 then return false end
 end
 return true
end
function D.actorRoot(ram)
 if D.root and rootsValid(ram,D.root)then return D.root end
 local p=offset(u32(ram+0xab9f4),0x100)-0x20
 local seen={}
 for _=1,512 do
  assert(not seen[p],'Actor predecessor cycle');seen[p]=true
  local h=header(ram,p)
  if h.prev==0 then
   local roots={}
   for level=0,8 do local r=p-level*0x44;if rootsValid(ram,r)then roots[#roots+1]=r end end
   assert(#roots==1,'Actor-list root not uniquely identified');D.root=roots[1];return D.root
  end
  p=offset(h.prev,32)
 end
 error('Actor predecessor chain exceeds limit')
end
function D.actors(ram)
 local root=D.actorRoot(ram);local start=root+4*0x44;local finish=start+0x20
 local previous=start;local pointer=u32(ram+start+4);local result={};local seen={}
 for _=1,512 do
  local o=offset(pointer,32)
  if o==finish then
   assert(u32(ram+finish)==0x80000000+previous,'Actor tail changed during enumeration')
   return result
  end
  assert(not seen[o],'Actor-list cycle');seen[o]=true
  local h=header(ram,o)
  assert(h.prev==0x80000000+previous,'Actor list changed while reading')
  if h.act&gt;=0x800c0000 and h.act&lt;0x80200000 and h.die&gt;=0x800c0000 and h.die&lt;0x80200000 then
   local ok,n=pcall(function()return readString(ram+offset(h.namePointer,1),48)end)
   if ok and n then h.name=n;result[#result+1]=h end
  end
  previous=o;pointer=h.next
 end
 error('Actor count exceeds limit')
end
local function binary(ram,start,size)
 local parts={}
 for o=0,size-1,8192 do
  local n=math.min(8192,size-o);local b=assert(readBytes(ram+start+o,n,true),'Overlay read unavailable')
  assert(#b==n,'Short overlay read');parts[#parts+1]=string.char(table.unpack(b))
 end
 return table.concat(parts)
end
function D.overlay(ram)
 local code={start=0xc0000,size=0xa0000}
 code.bytes=binary(ram,code.start,code.size)
 function code.word(o)
  if o&lt;code.start or o+4&gt;code.start+code.size or o%4~=0 then return nil end
  return string.unpack('&lt;I4',code.bytes,o-code.start+1)
 end
 return code
end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function imm(w)local n=w&amp;0xffff;return n&gt;=32768 and n-65536 or n end
local function absolute(code,p,w)
 local base=rs(w)
 for back=1,3 do
  local h=code.word(p-back*4)
  if h and op(h)==15 and rt(h)==base then
   local a=((h&amp;0xffff)&lt;&lt;16)+imm(w)
   if a&gt;=0x800c0000 and a&lt;0x80200000 then return a&amp;0x1fffff end
  end
 end
end
local function guardGateProof(code)
 local found={}
 for p=code.start,code.start+code.size-12,4 do
  local w=code.word(p)
  if (op(w)==36 or op(w)==32)and (w&amp;0xffff)==0xba3 then
   for j=1,2 do
    local a=code.word(p+4*j)
    if a and op(a)==12 and rs(a)==rt(w)then found[a&amp;0xffff]=true end
   end
  end
 end
 return found[1]and found[4]and found[16]
end
function D.reachable(code,entry)
 local pending={entry&amp;0x1fffff};local head=1;local seen={};local words={};local functions=0
 while head&lt;=#pending and functions&lt;180 do
  local fn=pending[head];head=head+1
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;functions=functions+1
   for p=fn,math.min(fn+0x2000,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if op(w)==3 then
     local target=((w&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if target&gt;=0x800c0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1fffff end
    end
    if w==0x3e00008 then words[p+4]=code.word(p+4);break end
   end
  end
 end
 return words
end
-- VR commander uses a materialized struct base, rather than absolute LHs.
function D.guardProfile(ram,actors,code)
 local watchers={}
 for _,a in ipairs(actors)do if a.name=='watcher.c'then watchers[a.offset]=a end end
 if not next(watchers)then return nil,'No standard guards loaded'end
 if not guardGateProof(code)then return nil,'Guard sensing layout not recognized'end
 local function s(n)return n&gt;=32768 and n-65536 or n end
 local function word(p)return code.word(p)end
 local function hi(w)return (w&amp;0xFFFF)&lt;&lt;16 end
 local matches={}
 for p=code.start,code.start+code.size-0x148,4 do
  local a,b,c,d,e,f,g,h,i,j,k=word(p),word(p+4),word(p+8),word(p+12),word(p+16),word(p+20),word(p+24),word(p+28),word(p+32),word(p+36),word(p+40)
  if a&amp;0xFFFF0000==0x3C020000 and b&amp;0xFFFF0000==0x24510000 and c&amp;0xFFFF0000==0x3C020000 and d==0x86230088 and e&amp;0xFFFF0000==0x3C040000 and f&amp;0xFFFF0000==0xAC430000 and g==0x8E020014 and h==0x246301F4 and i==0x284200FF and j&amp;0xFFFF0000==0x14400000 and k&amp;0xFFFF0000==0xAC830000 then
   local command=(hi(a)+s(b&amp;0xFFFF))&amp;0x1FFFFF
   local eye=(hi(c)+s(f&amp;0xFFFF))&amp;0x1FFFFF
   local shoot=(hi(e)+s(k&amp;0xFFFF))&amp;0x1FFFFF
   if command==eye+12 and shoot==eye-4 then
    local configs={}
    for q=p+44,p+0x148-16,4 do
     local load=word(q)
     if load==0x8623008A or load==0x8623008C then
      for z=q+4,q+16,4 do
       local store=word(z)
       if store==f then configs[load&amp;0xFFFF]=true end
      end
     end
    end
    local vision
    for _,actor in pairs(watchers)do
     for q in pairs(D.reachable(code,actor.act))do
      local w=word(q)
      if w==0x244207D0 and word(q+4)==0x0052102A then
       local load=word(q-8);local upper=word(q-12)
       if load and upper and load&amp;0xFFFF0000==0x8C420000 and upper&amp;0xFFFF0000==0x3C020000 and ((hi(upper)+s(load&amp;0xFFFF))&amp;0x1FFFFF)==eye then vision=q end
      end
     end
    end
    local count,mode=u32(ram+command+8),u32(ram+command+0x18)
    local matched=0
    if configs[0x8A]and configs[0x8C]and vision and count&lt;=8 and mode&lt;=2 then
     for slot=0,7 do
      local ptr=u32(ram+command+0xD4+slot*0x10)
      local actor=ptr&gt;=0x80000000 and ptr&lt;0x80200000 and watchers[ptr&amp;0x1FFFFF]
      if actor and readBytes(ram+actor.offset+0xB78,1)==slot then matched=matched+1 end
     end
     if matched&gt;0 then
      matches[#matches+1]={command=command,eye=eye,shoot=shoot,ranges=command+0x88,visionPC=vision,matched=matched,
       blocks={{offset=p,bytes=code.bytes:sub(p-code.start+1,p-code.start+0x148)}}}
     end
    end
   end
  end
 end
 if #matches~=1 then return nil,'Integral guard commander mapping is not unique ('..#matches..')'end
 return matches[1]
end
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
function D.cameraProfile(actor,code)
 if not cameraNames[actor.name]then return nil end
 local pending={actor.act&amp;0x1fffff};local seen={};local candidates={};local examined=0
 while #pending&gt;0 and examined&lt;100 do
  local fn=table.remove(pending)
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;examined=examined+1
   local words={};local workRegisters={}
   for p=fn,math.min(fn+0x1800,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if p&lt;fn+0x60 and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if (rs(w)==4 and rt(w)==0)or(rs(w)==0 and rt(w)==4)then workRegisters[rd(w)]=true end
    end
    if op(w)==3 then
     local target=((w&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if target&gt;=0x800c0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1fffff end
    end
    if w==0x3e00008 then words[p+4]=code.word(p+4);break end
   end
   for p,w in pairs(words)do
    if op(w)==3 and (((w&amp;0x3ffffff)&lt;&lt;2)|0x80000000)==0x80016e84 then
     for j=1,7 do
      local compare=words[p+j*4]
      if compare and op(compare)==0 and (compare&amp;63)==42 and rt(compare)==2 then
       local rangeRegister=rs(compare)
       for back=p+j*4-4,math.max(fn,p-0x40),-4 do
        local load=words[back]
        if load and (op(load)==37 or op(load)==35)and rt(load)==rangeRegister and workRegisters[rs(load)]then
         local field=load&amp;0xffff;local size=op(load)==37 and 2 or 4
         if field&gt;=0x100 and field&lt;0x800 then
          local width=false
          for q,z in pairs(words)do if q&lt;p and op(z)==op(load)and rs(z)==rs(load)and (z&amp;0xffff)==field+size then width=true end end
          if width then candidates[field]={range=field,size=size,detector=fn,loadPC=back}end
         end
         break
        end
       end
      end
     end
    end
   end
  end
 end
 local profiles={};for _,v in pairs(candidates)do profiles[#profiles+1]=v end
 if #profiles~=1 then return nil,'Camera distance check is not unique ('..#profiles..')'end
 return profiles[1]
end
function D.guardActors(ram,actors,profile)
 local result={};if not profile then return result end
 local present={};for _,a in ipairs(actors)do present[a.offset]=a end
 for i=0,7 do
  local p=u32(ram+profile.command+0xc8+i*0x10+0xc)
  if p&gt;=0x80000000 and p&lt;0x80200000 then
   local a=present[p&amp;0x1fffff]
   if a and a.name=='watcher.c'and readBytes(ram+a.offset+0xb78,1)==i then a.slot=i;result[a.offset]=a end
  end
 end
 return result
end
return D
]====]):sub(2),
 [ [====[Integral/int-guard-proximity.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- CE-side proximity modes for standard guards: knockout or kill.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTGuardProximity and INTGuardProximity.pid==getOpenedProcessID()and INTGuardProximity.version==5 then return INTGuardProximity end
if INTGuardProximity then INTGuardProximity.stop()end
local A=dofile(dir..'int-guard-state.lua')
local C={version=5,pid=A.pid,actions=A,enabled=false,mode=nil,radius=A.validateRadius(INTProximityRadius or 3000),affected=0,batches=0,status='Proximity OFF'}
local ids={knockout=510,kill=511}
local prefixes={knockout='Proximity auto knockout',kill='Proximity auto kill'}
local function record(mode)
 local row=getAddressList().getMemoryRecordByID(ids[mode])
 return row and row.Description:find(prefixes[mode],1,true)==1 and row or nil
end
local function now()return getTickCount()end
function C.setRadius(value)
 C.radius=A.validateRadius(value);INTProximityRadius=C.radius
 C.status=C.enabled and (C.mode..' ON | radius '..C.radius..' | waiting for nearby guards')or ('Proximity OFF | radius '..C.radius)
 return C.radius
end
function C.disable(mode)
 if mode and C.mode~=mode then return true end
 C.enabled=false;C.mode=nil
 if C.timer then C.timer.Enabled=false end
 C.state=nil;C.nextAction=nil;C.epoch=nil;C.nextCheck=nil
 C.status='Proximity OFF | radius '..C.radius
 for _,kind in ipairs({'knockout','kill'})do local row=record(kind);if row and row.Active then row.Active=false end end
 return true
end
local function audit(result)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/integral-guard-proximity-actions.csv','a+'))
  local success,why=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Proximity action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,mode,radius,slot,actor,distance,hp_before,faint_before\n'))end
   for _,g in ipairs(result.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%d,%d,%08X,%.1f,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),C.pid,result.stage,result.mode,result.radius,g.actor.slot,0x80000000+g.actor.offset,g.distance,g.hp,g.faint)))end end
  end)
  f:close();assert(success,why)
 end)
 if not ok then C.logError=tostring(err)end
end
function C.tick()
 if not C.enabled or C.busy then return end
 if getOpenedProcessID()~=C.pid then C.disable();C.status='Stopped: process changed. Re-enable for the new process.';return end
 local time=now();if C.nextCheck and time&lt;C.nextCheck then return end
 C.busy=true
 local ok,err=pcall(function()
  local c=A.nearby(C.radius);C.state=c
  local epoch=c.ram..':'..c.stage
  if C.epoch~=epoch then C.epoch=epoch;C.nextAction=nil end
  C.status=string.format('%s ON | radius %d | %s | %d nearby, %d ready | %d affected',C.mode,C.radius,c.stage,c.inRange,c.nearEligible,C.affected)
  if c.nearEligible&gt;0 and (not C.nextAction or time&gt;=C.nextAction)then
   local result=A.apply(C.mode,{radius=C.radius})
   C.last=result;C.affected=C.affected+result.affected;C.batches=C.batches+1;C.nextAction=now()+1000
   C.status=string.format('%s ON | radius %d | %s | applied to %d guards (%d total)',C.mode,C.radius,result.stage,result.affected,C.affected)
   audit(result)
  end
 end)
 C.busy=false
 if not ok then
  -- Loading, menus, cutscenes, unsupported layouts or moving targets wait for
  -- a new valid context. No stale actor list is used and no dialog steals focus.
  C.state=nil;C.lastError=tostring(err);C.status='Waiting: '..C.lastError;C.nextCheck=now()+1000
 else C.lastError=nil;C.nextCheck=nil end
end
function C.enable(mode)
 assert(ids[mode],'Unknown proximity mode.')
 assert(not C.stopped and getOpenedProcessID()==C.pid,'Reopen proximity controls for this process.')
 if C.enabled and C.mode==mode then return true end
 C.disable();C.mode=mode;C.enabled=true;C.lastError=nil
 if not C.timer then C.timer=createTimer(nil,false);C.timer.Interval=500;C.timer.OnTimer=C.tick end
 -- Enabling the other AA entry must uncheck this entry without stopping the
 -- replacement mode. disable(mode) above is conditional on the current mode.
 C.status=mode..' ON | radius '..C.radius..' | checking every 500 ms'
 C.timer.Enabled=true
 return true
end
function C.stop()
 C.disable();C.stopped=true
 if C.timer then C.timer.destroy();C.timer=nil end
 if INTGuardProximity==C then INTGuardProximity=nil end
 return true
end
INTGuardProximity=C
return C
]====]):sub(2),
 [ [====[Integral/int-guard-state.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Optional one-shot outcomes for standard watcher.c guards. No injected calls.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local D=dofile(dir..'int-discovery.lua')
local B=dofile(dir..'int-ownership.lua')
local A={version=2,pid=R.pid,status='Choose a one-shot guard action.'}
local nativeCache
local function u16(a)return assert(readSmallInteger(a),'Guard short unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Guard word unavailable')&amp;0xffffffff end
local function bytes(a,n)
 local out={};for j=0,n-1,4096 do
  local k=math.min(4096,n-j);local b=assert(readBytes(a+j,k,true),'Guard code unavailable');assert(#b==k)
  out[#out+1]=string.char(table.unpack(b))
 end;return table.concat(out)
end
local function hex(s)return s:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function context()
 assert(getOpenedProcessID()==A.pid,'Attached process changed; reopen the guard panel.')
 local h=R.read();local r=h.ram
 assert(h.health&gt;0 and u32(r+0xab3d0)==0 and u32(r+0xaba38)~=0 and u32(r+0xab3d4)==0,'Wait for living, normal gameplay.')
 assert(u32(r+0xab3cc)&amp;0xd40c0000==0 and u32(r+0xaba50)&amp;0x20002084==0,'Finish the scene or restricted action first.')
 local control=u32(r+0xab9f4)
 assert(control&gt;=0x80000020 and control&lt;0x801ff000,'Normal Snake is not loaded.')
 local snake=(control&amp;0x1fffff)-0x20
 assert(u32(r+snake+8)==0x8005ad10 and u32(r+snake+12)==0x8005b52c and u32(r+0xaba20)==0x80000000+snake+0x9c,'Snake actor differs.')
 assert(u32(r+0xbd360+8)==0x800386a4 and u32(r+0xbd360+12)==0x800387e8 and u16(r+0xbd360+0x2a)==0,'Close the game menu first.')
 local stage=assert(readString(r+0xb4d88,16))
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Area is not ready.')
 return {ram=r,stage=stage,h=h,snake=snake}
end
local function damageProfile(code)
 local header=hex('E0FFBD271000B0AF218080001800BFAF1400B1AF0009118E0000000006002296')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'VR guard damage handler is missing or ambiguous')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'VR guard damage branches differ')end
 match(0x20,'000000000400423067004010211000003E00229600000000FFFF422400140200031C02000900622C5C004010')
 match(0x54,'80180300211862000000628C000000000800400000000000')
 local upper,lower=code.word(fn+0x4c),code.word(fn+0x50)
 assert(upper&amp;0xffff0000==0x3c020000 and lower&amp;0xffff0000==0x24420000,'VR guard switch layout differs')
 local tablePSX=((upper&amp;0xffff)&lt;&lt;16)+signed(lower&amp;0xffff)
 assert(tablePSX&gt;=0x800c0000 and tablePSX+36&lt;=0x80160000,'VR damage switch outside overlay')
 local t=tablePSX&amp;0x1fffff
 assert(code.word(t)==0x80000000+fn+0xe4 and code.word(t+8)==0x80000000+fn+0x6c,'VR lethal/stun mode routing differs')
 match(0x94,'2A002286000000000700401C9C0004262128000001000224DC0802AE')
 match(0x10c,'26002286000000000700401C9C0004262128000001000224DC0802AE')
 match(0x1a8,'EC0802AEF40800AE700000A6')
 match(0x1c0,'280020A6060020A6')
 return {fn=fn,tableOffset=t,code=code.bytes:sub(start,start+0x1dc-1),switch=code.bytes:sub(t-code.start+1,t-code.start+36)}
end
local function recoveryProfile(code)
 local header=hex('D8FFBD271800B0AF218080002000BFAF1C00B1AF700B028E2188A00020004234')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'Guard knockout recovery handler differs.')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'Guard knockout timer layout differs.')end
 match(0x100,'5A0B02A6')
 match(0x1b8,'5A0B0286000000002A1051001200401000000000')
 match(0x1cc,'0009038E000000002A006284000000000400401C9C000426840B0296000000002A0062A4')
 return {fn=fn,code=code.bytes:sub(start,start+0x228-1)}
end
function A.inspect(useCache)
 local c=context();local r=c.ram
 local actors=D.actors(r)
 c.guards={};c.eligible=0;c.knockedOut=0;c.dead=0;c.skipped=0;c.total=0
 local identity={};local watchers=0
 for _,a in ipairs(actors)do if a.name=='watcher.c'or a.name=='command.c'then
  identity[#identity+1]=a.name..':'..a.offset..':'..a.act..':'..a.die..':'..bytes(r+(a.act&amp;0x1fffff),32)
  if a.name=='watcher.c'then watchers=watchers+1 end
 end end
 if watchers==0 then nativeCache=nil;c.reason='No standard guards loaded';return c end
 table.sort(identity);local key=r..':'..c.stage..':'..table.concat(identity,'|')
 local cached=useCache and nativeCache and nativeCache.key==key and nativeCache or nil
 if cached and bytes(cached.proof.address,32)~=cached.proof.bytes then cached=nil end
 local code=cached and cached.code or D.overlay(r)
 local profile,why
 if cached then profile=cached.profile else profile,why=D.guardProfile(r,actors,code)end
 if not profile then c.reason=why;return c end
 c.profile=profile;c.damage=cached and cached.damage or damageProfile(code);c.recovery=cached and cached.recovery or recoveryProfile(code);c.ownership={}
 c.profileProof={address=r+profile.visionPC-12,bytes=bytes(r+profile.visionPC-12,32)}
 local families=cached and cached.families or {};local reachable=cached and cached.reachable or {};local retained={};local targets={}
 for _,actor in pairs(D.guardActors(r,actors,profile))do
  local w=actor.offset
  assert(actor.name=='watcher.c'and w~=c.snake and w&gt;=0x10000 and w+0xc4c&lt;=0x200000,'Guard ownership differs.')
  local family=actor.act..':'..actor.die;local e=families[family]
  if not e then e=B.ownership(r,actor);assert(e.targets[0x900],'Guard TARGET pointer lacks native ownership proof.');families[family]=e end
  if not retained[family]then c.ownership[#c.ownership+1]=e;retained[family]=true end
  local ptr=u32(r+w+0x900)
  assert(ptr&gt;=0x800b64e0 and ptr&lt;0x800b76e0 and (ptr-0x800b64e0)%0x48==0,'Guard target pool slot differs.')
  assert(not targets[ptr],'Two guards share a damage target.');targets[ptr]=true
  local t=r+(ptr&amp;0x1fffff);local hp,faint=u16(t+0x26),u16(t+0x2a)
  assert(u16(t+2)==2,'Guard target is not enemy-owned.')
  local g={actor=actor,pointer=ptr,target=t,hp=hp,faint=faint,class=u16(t),flags=u16(t+6),action=u32(r+w+0x8ec),status=u32(r+w+0xb70)}
  c.total=c.total+1
  if hp==0 or hp&gt;=32768 then g.reason='dead';c.dead=c.dead+1
  elseif faint==0 or faint&gt;=32768 then g.reason='knocked out / recovering';c.knockedOut=c.knockedOut+1
  elseif g.class&amp;4==0 or g.flags&amp;6~=0 or u16(t+0x42)~=0 or u16(r+w+0xc2c)~=0 then g.reason='busy / not accepting damage';c.skipped=c.skipped+1
  else
   local accepts=reachable[g.action]
   if accepts==nil then accepts=g.action&gt;=0x800c0000 and g.action&lt;0x80160000 and D.reachable(code,g.action)[c.damage.fn]~=nil;reachable[g.action]=accepts end
   if accepts then g.eligible=true;c.eligible=c.eligible+1
   else g.reason='current action has no verified damage path';c.skipped=c.skipped+1 end
  end
  c.guards[#c.guards+1]=g
 end
 table.sort(c.guards,function(a,b)return a.actor.slot&lt;b.actor.slot end)
 nativeCache={key=key,code=code,profile=profile,damage=c.damage,recovery=c.recovery,proof=c.profileProof,families=families,reachable=reachable}
 return c
end
function A.validateRadius(radius)
 radius=tonumber(radius)
 assert(radius and radius==math.floor(radius)and radius&gt;=100 and radius&lt;=20000,'Radius must be a whole number from 100 to 20000 game units.')
 return radius
end
local function distance(r,snake,actor)
 local squared=0
 for i=0,2 do
  local delta=signed(u16(r+snake+0x20+i*2))-signed(u16(r+actor+0x20+i*2))
  squared=squared+delta*delta
 end
 return math.sqrt(squared)
end
function A.nearby(radius)
 radius=A.validateRadius(radius)
 -- Cached scans only nominate candidates. A.apply always rediscovers native
 -- evidence from current RAM and checks range again before any target write.
 local c=A.inspect(true);c.radius=radius;c.inRange=0;c.nearEligible=0
 for _,g in ipairs(c.guards)do
  g.distance=distance(c.ram,c.snake,g.actor.offset);g.inRange=g.distance&lt;=radius
  if g.inRange then c.inRange=c.inRange+1;if g.eligible then c.nearEligible=c.nearEligible+1 end end
 end
 return c
end
function A.apply(mode,options)
 assert(mode=='kill'or mode=='knockout','Choose kill or knockout.')
 options=options or {};local radius=options.radius and A.validateRadius(options.radius)or nil
 local c=A.inspect()
 if radius then
  c.eligible=0
  for _,g in ipairs(c.guards)do if g.eligible then
   g.distance=distance(c.ram,c.snake,g.actor.offset)
   if g.distance&lt;=radius then c.eligible=c.eligible+1 else g.eligible=false;g.reason='outside proximity radius'end
  end end
 end
 assert(c.eligible&gt;0,'No eligible standard guards. '..(c.reason or 'Already down, busy, outside radius, or unsupported.'))
 local writes,notifications={},{}
 local function plan(a,v,label)
  writes[#writes+1]={address=a,before=u16(a),value=v,label=label}
 end
 for _,g in ipairs(c.guards)do if g.eligible then
  local t=g.target
  plan(t+0x3e,mode=='kill'and 1 or 3,'damage mode')
  if mode=='kill'then plan(t+0x26,0,'vital')else plan(t+0x2a,0,'faint')end
  plan(t+0x28,mode=='kill'and g.hp or 0,'damage amount')
  for _,o in ipairs({0x2c,0x2e,0x30})do plan(t+o,0,'impact force')end
  notifications[#notifications+1]={address=t+6,before=g.flags,value=g.flags|4,label='damage notification'}
 end end
 -- Validate the whole batch before any writes; never reuse a previous area.
 local fresh=context();assert(fresh.ram==c.ram and fresh.stage==c.stage and fresh.snake==c.snake,'Area/player changed; refresh.')
 assert(bytes(c.ram+c.damage.fn,#c.damage.code)==c.damage.code and bytes(c.ram+c.damage.tableOffset,36)==c.damage.switch,'Guard damage code changed.')
 assert(bytes(c.profileProof.address,32)==c.profileProof.bytes,'Guard commander binding changed.')
 for _,block in ipairs(c.profile.blocks or {})do assert(bytes(c.ram+block.offset,#block.bytes)==block.bytes,'VR commander code changed.')end
 for _,e in ipairs(c.ownership)do for _,p in ipairs(e.blocks)do assert(bytes(p.address,#p.bytes)==p.bytes,'Guard native ownership code changed.')end end
 for _,g in ipairs(c.guards)do if g.eligible then
  local a,t=g.actor,g.target;local w=c.ram+a.offset
  assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+20)==a.namePointer and readString(c.ram+(a.namePointer&amp;0x1fffff),48)=='watcher.c','Guard actor changed.')
  assert(u32(c.ram+c.profile.command+0xc8+a.slot*0x10+0xc)==0x80000000+a.offset and readBytes(w+0xb78,1)==a.slot,'Commander no longer owns guard.')
  assert(u32(w+0x900)==g.pointer and u32(w+0x8ec)==g.action,'Guard target/action changed; retry.')
  assert(u16(t)==g.class and u16(t+2)==2 and u16(t+0x26)==g.hp and u16(t+0x2a)==g.faint and u16(t+0x42)==0 and u16(w+0xc2c)==0,'Guard damage state changed; retry.')
  if radius then assert(distance(c.ram,c.snake,a.offset)&lt;=radius,'Guard moved outside the proximity radius; retry.')end
 end end
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do assert(u16(v.address)==v.before,'Guard state changed; retry.')end end
 local count=0
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do
  assert(writeSmallInteger(v.address,v.value),'Guard write failed after '..count..' writes.');count=count+1
 end end
 A.last={mode=mode,pid=A.pid,ram=c.ram,stage=c.stage,affected=c.eligible,skipped=c.total-c.eligible,writes=count,guards=c.guards,recovery=c.recovery,command=c.profile.command,radius=radius}
 A.status=string.format('%s requested for %d guards; %d skipped. Resume gameplay.',mode,c.eligible,c.total-c.eligible)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/integral-guard-state-actions.csv','a+'))
  local success,problem=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Guard action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,action,guard,target,hp_before,faint_before\n'))end
   for _,g in ipairs(c.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%08X,%08X,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),A.pid,c.stage,mode,0x80000000+g.actor.offset,g.pointer,g.hp,g.faint)))end end
  end)
  f:close();assert(success,problem)
 end)
 if not ok then A.logError=tostring(err)end
 INTGuardState=A;return A.last
end
function A.extendKnockout(result,ticks)
 assert(result==A.last and result.mode=='knockout','A fresh knockout result is required.')
 assert(type(ticks)=='number'and ticks==math.floor(ticks)and ticks&gt;=30 and ticks&lt;=10000,'Invalid recovery delay.')
 if A.extension then A.extension.stop()end
 local T={extended=0,stopped=false,remaining={},writes={}};A.extension=T
 for _,g in ipairs(result.guards)do if g.eligible then T.remaining[#T.remaining+1]=g end end
 local start=getTickCount();local timer=createTimer(nil,false);timer.Interval=100;T.timer=timer
 function T.stop()if not T.stopped then T.stopped=true;timer.Enabled=false;timer.destroy()end end
 function T.tick()
  if T.stopped then return end
  local ok,err=pcall(function()
   local c=context();assert(c.ram==result.ram and c.stage==result.stage,'Area changed; recovery extension cancelled.')
   local r=c.ram;assert(bytes(r+result.recovery.fn,#result.recovery.code)==result.recovery.code,'Recovery code changed.')
   for i=#T.remaining,1,-1 do
    local g=T.remaining[i];local a=g.actor;local w=r+a.offset
    assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+0x900)==g.pointer,'Guard owner changed.')
    assert(u32(r+result.command+0xc8+a.slot*0x10+0xc)==0x80000000+a.offset and readBytes(w+0xb78,1)==a.slot,'Guard commander changed.')
    assert(u16(g.target+2)==2 and u16(g.target+0x26)==g.hp,'Guard health/side changed.')
    local time=u32(w+0x8f4)
    if u32(w+0x8ec)==0x80000000+result.recovery.fn and time&gt;=1 and time&lt;32767-ticks and u16(g.target+0x2a)==0 and u16(g.target+0x42)==0 and u32(w+0xb70)&amp;0x20~=0 then
     local old=u16(w+0xb5a);assert(old&lt;32768,'Recovery threshold differs.')
     local value=math.max(old,time+ticks)
     assert(writeSmallInteger(w+0xb5a,value),'Recovery delay write failed.')
     T.writes[#T.writes+1]={actor=a.offset,before=old,after=value};T.extended=T.extended+1;table.remove(T.remaining,i)
    end
   end
   if #T.remaining==0 then A.status='Extended knockout applied to '..T.extended..' guards; they will recover normally.';T.stop()end
  end)
  if not ok then T.error=tostring(err);A.status='Recovery extension stopped: '..T.error;T.stop()
  elseif getTickCount()-start&gt;=15000 then T.error='Timed out waiting for guards to reach the floor.';A.status=T.error;T.stop()end
 end
 timer.OnTimer=T.tick;timer.Enabled=true
 A.status='Knockout requested; waiting to extend the normal recovery timers.'
 return T
end
INTGuardState=A
return A
]====]):sub(2),
 [ [====[Integral/int-inventory.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- One-shot inventory grants and normal game equipment-selection requests.
-- All weapon/item slots are selectable, including equipment not yet owned.
if INTInventory and INTInventory.pid==getOpenedProcessID()then return INTInventory end
if INTInventory and INTInventory.closeLog then INTInventory.closeLog()end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local G={pid=R.pid,reader=R,version=1,pending={},status='Choose equipment to add to inventory.'}
G.weapons={
 {id=0,name='SOCOM',stock=25},{id=1,name='FAMAS',stock=100},
 {id=2,name='Grenade',stock=8},{id=3,name='Nikita',stock=10},
 {id=4,name='Stinger',stock=10},{id=5,name='Claymore',stock=8},
 {id=6,name='C4',stock=8},{id=7,name='Stun grenade',stock=8},
 {id=8,name='Chaff grenade',stock=8},{id=9,name='PSG1',stock=10},
}
G.gadgets={
 {id=0,name='Cigarettes'},{id=1,name='Binoculars'},
 {id=2,name='Cardboard box A'},{id=3,name='Cardboard box B'},{id=4,name='Cardboard box C'},
 {id=5,name='Night-vision goggles'},{id=6,name='Thermal goggles'},
 {id=7,name='Gas mask'},{id=8,name='Body armor'},{id=9,name='Ketchup'},
 {id=10,name='Stealth camouflage'},{id=11,name='Bandana'},{id=12,name='Camera'},
 {id=13,name='Rations',kind='consumable',stock=5},
 {id=14,name='Cold medicine',kind='consumable',stock=5},
 {id=15,name='Diazepam',kind='consumable',stock=5},
 {id=16,name='PAL key',note='Adds the PAL key. Its temperature/state stays under game control.'},
 {id=17,name='Key card',kind='level',stock=7,note='Choose an access level from 1 to 7.'},
 {id=18,name='Time bomb (story countdown)',kind='timer',stock=30000,equipable=false,
  note='Story time-bomb value. Adding it can start a countdown; the value uses game timer units.'},
 {id=19,name='Mine detector'},{id=20,name='MO disk'},{id=21,name='Rope'},
 {id=22,name='Handkerchief'},
 {id=23,name='SOCOM suppressor',equipable=false,note='Adds the suppressor. SOCOM attaches it through the normal weapon update.'},
}
local function u16(a)return assert(readSmallInteger(a),'Inventory read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Game state unavailable')&amp;0xffffffff end
local function signed32(v)return v&gt;=0x80000000 and v-0x100000000 or v end
local function owned(raw)return raw~=0xffff end
local function amount(raw)return owned(raw)and (raw&amp;0x7fff)or 0 end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xffff),'Inventory write failed')end
local function fingerprint(a,expected)
 local b=assert(readBytes(a,#expected,true),'Equipment-switch code unavailable')
 for i,v in ipairs(expected)do assert(b[i]==v,'Equipment-switch layout differs')end
end
local function entry(kind,id)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Select valid equipment')
 local list=kind=='weapon'and G.weapons or G.gadgets
 local e=list[id+1];assert(e and e.id==id,'Equipment ID out of range')
 return e
end
function G.context(writing)
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xab3d0)==0 and u32(ram+0xaba38)~=0,'Wait for area loading to finish.')
 local control=u32(ram+0xab9f4)
 assert(control&gt;=0x80000020 and control&lt;0x80200000,'Snake is not ready.')
 local work=(control&amp;0x1fffff)-0x20
 assert(work+0xa28&lt;0x200000,'Snake actor bounds differ.')
 assert(u32(ram+work+8)==0x8005ad10 and u32(ram+work+12)==0x8005b52c,'Wait for normal gameplay.')
 assert(u32(ram+0xaba20)==0x80000000+work+0x9c,'Snake body ownership differs.')
 local flags=u32(ram+0xab3cc);local player=u32(ram+0xaba50)
 local ready=h.health&gt;0 and u32(ram+0xab3d4)==0 and flags&amp;0xd40c0000==0 and player&amp;0x20002084==0
 if writing then assert(ready,'Finish the cutscene or restricted action first.')end
 return {h=h,ram=ram,work=work,ready=ready,frame=u32(ram+0xab9e8),
  activeWeapon=signed32(u32(ram+work+0x91c)),activeGadget=signed32(u32(ram+work+0x9a8)),
  stage=readString(ram+0xb4d88,16)or '?'}
end
local function log(kind,e,requested,actual,equipping,c)
 local ok,err=pcall(function()
  if not G.log then
   G.logPath=dir..'../../logs/integral-inventory-actions-'..G.pid..'.csv'
   G.log=assert(io.open(G.logPath,'a'))
   if G.log:seek()==0 then G.log:write('utc,stage,category,id,name,requested,actual,equip\n')end
  end
  local name='"'..e.name:gsub('"','""')..'"'
  assert(G.log:write(table.concat({os.date('!%Y-%m-%dT%H:%M:%SZ'),c.stage,kind,e.id,name,requested,actual,equipping and 1 or 0},',')..'\n'))
  G.log:flush()
 end)
 if not ok then G.logError=tostring(err)end
end
function G.closeLog()
 if G.log then G.log:close();G.log=nil end
end
function G.equip(kind,id,c)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Equipment ID must be an integer')
 local e=id==-1 and {id=-1,name='Nothing'}or entry(kind,id)
 assert(e.equipable~=false,'Add this item to inventory; it is not directly equipped.')
 c=c or G.context(true)
 R.checkFeature('inventory')
 local address=kind=='weapon'and 0xb4dba or 0xb4de2
 if id&gt;=0 then assert(owned(u16(c.ram+address+id*2)),'Add the selected equipment first.')end
 -- These are the same requested slots used by the normal inventory menu.
 -- The game creates/removes equipment actors and updates its active caches.
 local slot=kind=='weapon'and 0xb4db4 or 0xb4db6
 put16(c.ram+slot,id)
 G.pending[kind]={id=id,name=e.name,ram=c.ram,work=c.work,frame=c.frame}
 G.status=e.name..' selected. Resume gameplay to finish equipping.'
 return true
end
function G.grant(kind,id,quantity,equipping)
 local e=entry(kind,id)
 assert(not equipping or e.equipable~=false,'This item is added to inventory without equipping.')
 quantity=tonumber(quantity or e.stock or 1)
 local maximum=kind=='weapon'and 9999 or e.kind=='level'and 7 or e.kind=='timer'and 32767 or e.kind=='consumable'and 9999 or 1
 assert(quantity and quantity==math.floor(quantity)and quantity&gt;=1 and quantity&lt;=maximum,'Amount must be a whole number from 1 to '..maximum..'.')
 local c=G.context(true)
 R.checkFeature('inventory')
 local base=kind=='weapon'and 0xb4dba or 0xb4de2
 local address=c.ram+base+id*2;local raw=u16(address)
 local value=(kind=='weapon'or e.kind)and math.max(amount(raw),quantity)or 1
 assert(value&lt;32768,'Existing inventory count is invalid.')
 local capacity
 if kind=='weapon'then capacity=c.ram+0xb4dce+id*2
 elseif e.kind=='consumable'then capacity=c.ram+0xb4de2+(id+11)*2 end
 if capacity then
  local old=u16(capacity);if old&gt;=32768 then old=0 end
  if old&lt;value then put16(capacity,value)end
 end
 put16(address,value)
 local actual=u16(address)
 assert(owned(actual),'Game did not retain the inventory entry.')
 G.status=e.name..' added to inventory.'
 if equipping then G.equip(kind,id,c)end
 log(kind,e,quantity,actual,equipping,c)
 return {id=id,name=e.name,value=actual,capacity=capacity and u16(capacity)or nil,equipping=not not equipping}
end
function G.inspect()
 local c=G.context(false);c.inventory={}
 for _,e in ipairs(G.gadgets)do c.inventory[e.id]=u16(c.ram+0xb4de2+e.id*2)end
 for kind,p in pairs(G.pending)do
  local actual=kind=='weapon'and c.activeWeapon or c.activeGadget
  local requested=kind=='weapon'and c.h.weapon or c.h.item
  if actual==p.id then
   G.status=p.name..' equipped.';G.pending[kind]=nil
  elseif c.ram~=p.ram or c.work~=p.work then
   G.status=p.name..' was added; the area changed before equipment was confirmed.';G.pending[kind]=nil
  elseif c.frame-p.frame&gt;180 and requested~=p.id then
   G.status=p.name..' is in inventory. The game selected different equipment.';G.pending[kind]=nil
  end
 end
 return c
end
G.entry=entry;G.owned=owned;G.amount=amount
INTInventory=G
return G
]====]):sub(2),
 [ [====[Integral/int-no-alert.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Data-only guard/camera suppression. Profiles are resolved from live MIPS code.
if INTNoAlert then
 assert(INTNoAlert.version==2 and INTNoAlert.pid==getOpenedProcessID(),'Stop the previous no-alert controller before upgrading')
 return INTNoAlert
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local D=dofile(dir..'int-discovery.lua')
local A={pid=R.pid,reader=R,discovery=D,version=2,enabled=false,wanted=false,status='OFF',rebinds=0,cache={}}
local MASK=0x17
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
local function u16(a)return assert(readSmallInteger(a),'Short read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Word read unavailable')&amp;0xffffffff end
local function byte(a)return assert(readBytes(a,1),'Byte read unavailable')end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xffff),'Short write failed')end
local function put32(a,v)assert(writeInteger(a,v&amp;0xffffffff),'Word write failed')end
local function put8(a,v)assert(writeBytes(a,v&amp;255),'Byte write failed')end
local function stamp(ram,p,n)
 local b=assert(readBytes(ram+p,n or 16,true),'Code fingerprint unavailable')
 return string.char(table.unpack(b))
end
local function blocksValid(r,p)
 for _,b in ipairs(p.blocks or {})do if stamp(r,b.offset,#b.bytes)~=b.bytes then return false end end
 return true
end
local function family(a)return a.name..':'..a.act..':'..a.die end
local function actorSame(a,b)return a and b and a.offset==b.offset and a.act==b.act and a.die==b.die and a.name==b.name end
local function now()return getTickCount and getTickCount()or math.floor(os.clock()*1000)end
function A.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xab3d0)==0 and u32(ram+0xaba38)~=0,'Area loading')
 local stage=assert(readString(ram+0xb4d88,16),'Stage unavailable')
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Stage not ready')
 local actors=D.actors(ram);local present={};local families={};local samples={}
 for _,a in ipairs(actors)do
  present[a.offset]=a
  if a.name=='watcher.c'or cameraNames[a.name]or a.name=='command.c'then
   local key=family(a)
   if not families[key]then families[key]=true;samples[#samples+1]=key..stamp(ram,a.act&amp;0x1fffff,32)end
  end
 end
 table.sort(samples)
 local epoch=tostring(ram)..':'..stage
 local key=epoch..':'..table.concat(samples,'|')
 local profile=A.cache[key]
 if profile then
  if profile.guard and not blocksValid(ram,profile.guard)then profile=nil end
  if profile and profile.guard and stamp(ram,profile.guard.proofPC,32)~=profile.guard.proof then profile=nil end
  if profile then for _,p in pairs(profile.cameras)do if stamp(ram,p.loadPC,16)~=p.proof then profile=nil;break end end end
 end
 if not profile or (profile.unsupported&gt;0 and now()-(profile.time or 0)&gt;1000)then
  local code=D.overlay(ram)
  profile={cameras={},unsupported=0,time=now()}
  local p,why=D.guardProfile(ram,actors,code);profile.guard=p;profile.guardReason=why
  local checked={}
  for _,a in ipairs(actors)do
   if a.name=='watcher.c'and not p then profile.unsupported=profile.unsupported+1 end
   if cameraNames[a.name]and not checked[family(a)]then
    checked[family(a)]=true
    local cp,err=D.cameraProfile(a,code)
    if cp then cp.proof=stamp(ram,cp.loadPC,16);profile.cameras[family(a)]=cp
    else profile.unsupported=profile.unsupported+1;profile.cameraReason=err end
   end
  end
  if p then p.proofPC=p.visionPC-12;p.proof=stamp(ram,p.proofPC,32)end
  A.cache[key]=profile
 end
 local c={ram=ram,stage=stage,epoch=epoch,key=key,h=h,actors=present,profile=profile,guards=D.guardActors(ram,actors,profile.guard),cameras={}}
 for _,a in ipairs(actors)do
  local cp=profile.cameras[family(a)]
  if cp then a.cameraProfile=cp;c.cameras[a.offset]=a end
 end
 return c
end
local function fresh(c)
 -- Stage/DRAM changes unload the previous area. Never restore through its old
 -- addresses into a replacement overlay or replacement actor allocation.
 if not A.snapshot or A.snapshot.epoch~=c.epoch then
  A.snapshot={epoch=c.epoch,ram=c.ram,stage=c.stage,guards={},cameras={}}
  A.rebinds=A.rebinds+1
 end
 local s=A.snapshot;local p=c.profile.guard
 if p then
  if not s.guard or s.guard.profile.command~=p.command or s.guard.profile.proof~=p.proof then
   s.guard={profile=p,ranges={}}
  end
  for i=0,2 do
   local v=u16(c.ram+p.ranges+i*2)
   if v~=0x8000 then assert(v&lt;32768,'Existing negative guard range');s.guard.ranges[i+1]=v end
   assert(s.guard.ranges[i+1]~=nil,'Guard ranges already modified without ownership')
  end
 end
 return s
end
local function apply(c)
 local s=fresh(c);local ng,nc=0,0
 if c.profile.guard then
  local p=c.profile.guard
  for i=0,2 do if u16(c.ram+p.ranges+i*2)~=0x8000 then put16(c.ram+p.ranges+i*2,0x8000)end end
  if u32(c.ram+p.eye)~=0xffff8000 then put32(c.ram+p.eye,0xffff8000)end
  for o,g in pairs(c.guards)do
   ng=ng+1;local flags=byte(c.ram+o+0xba3);local saved=s.guards[o]
   if not saved or not actorSame(saved.actor,g)or saved.actor.slot~=g.slot then saved={actor=g,mask=flags&amp;MASK};s.guards[o]=saved end
   saved.mask=saved.mask|(flags&amp;MASK)
   if flags&amp;MASK~=0 then put8(c.ram+o+0xba3,flags&amp;(~MASK&amp;255))end
   for _,field in ipairs({0xb92,0xb94})do if u16(c.ram+o+field)~=0 then put16(c.ram+o+field,0)end end
   if u32(c.ram+o+0xb98)~=0 then put32(c.ram+o+0xb98,0)end
   for _,field in ipairs({0xba1,0xba2})do if byte(c.ram+o+field)~=0 then put8(c.ram+o+field,0)end end
  end
 end
 for o,camera in pairs(c.cameras)do
  nc=nc+1;local cp=camera.cameraProfile
  local v=cp.size==4 and u32(c.ram+o+cp.range)or u16(c.ram+o+cp.range);local old=s.cameras[o]
  if not old or not actorSame(old.actor,camera)or old.field~=cp.range or old.size~=cp.size or old.proof~=cp.proof then
   old={actor=camera,field=cp.range,size=cp.size,range=v,proof=cp.proof,pc=cp.loadPC};s.cameras[o]=old
  elseif v~=0 then old.range=v end -- reinitialized/replaced camera parameters
  if v~=0 then if cp.size==4 then put32(c.ram+o+cp.range,0)else put16(c.ram+o+cp.range,0)end end
 end
 A.guardCount=ng;A.cameraCount=nc;A.stage=c.stage;A.profile=c.profile
 A.status=string.format('ON | %s | %d guards, %d cameras | area binds %d',c.stage,ng,nc,A.rebinds)
 if c.profile.unsupported&gt;0 then A.status=A.status..' | PARTIAL: unrecognized sensing layout'end
end
local function restore()
 if not A.snapshot then return end
 assert(getOpenedProcessID()==A.pid,'Original process required for cleanup')
 local c=A.context();local s=A.snapshot
 if c.epoch~=s.epoch then A.snapshot=nil;return end
 local p=s.guard and s.guard.profile
 if p and blocksValid(c.ram,p)and stamp(c.ram,p.proofPC,32)==p.proof then
  for i,v in ipairs(s.guard.ranges)do put16(c.ram+p.ranges+(i-1)*2,v)end
  local mode=u32(c.ram+p.command+0x18)
  if mode&lt;=2 then local r=s.guard.ranges[mode+1];put32(c.ram+p.eye,r);put32(c.ram+p.shoot,r+500)end
 end
 for o,old in pairs(s.guards)do
  local g=c.actors[o]
  if actorSame(g,old.actor)and byte(c.ram+o+0xb78)==old.actor.slot then
   put8(c.ram+o+0xba3,(byte(c.ram+o+0xba3)&amp;(~MASK&amp;255))|old.mask)
  end
 end
 for o,old in pairs(s.cameras)do
  if actorSame(c.actors[o],old.actor)and stamp(c.ram,old.pc,16)==old.proof then
   if old.size==4 then put32(c.ram+o+old.field,old.range)else put16(c.ram+o+old.field,old.range)end
  end
 end
 A.snapshot=nil
end
function A.disable()
 A.wanted=false;A.enabled=false
 local ok,err=pcall(restore)
 if not ok then A.status='CLEANUP WAITING: '..tostring(err);return false,A.status end
 A.status='OFF';return true
end
function A.enable()
 assert(not A.stopped,'Reload the stopped no-alert controller')
 if A.wanted then return true end
 assert(not A.snapshot,'Finish pending cleanup before enabling')
 local c=A.context()
 A.wanted=true;A.enabled=true
 local ok,err=pcall(apply,c)
 if not ok then A.disable();error(err)end
 return true
end
function A.tick()
 if A.stopped then return end
 if not A.wanted then if A.snapshot then A.disable()end;return end
 if getOpenedProcessID()~=A.pid then A.enabled=false;A.status='WAITING: original process required';return end
 local ok,err=pcall(function()apply(A.context())end)
 if ok then A.enabled=true else A.enabled=false;A.status='WAITING FOR AREA: '..tostring(err)end
end
function A.stop()
 local ok,err=A.disable();if not ok then return false,err end
 A.stopped=true;A.timer.Enabled=false;A.timer.destroy();A.timer=nil
 if INTNoAlert==A then INTNoAlert=nil end
 return true
end
A.timer=createTimer(nil,false);A.timer.Interval=50;A.timer.OnTimer=A.tick;A.timer.Enabled=true
INTNoAlert=A
return A
]====]):sub(2),
 [ [====[Integral/int-ownership.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
local B={}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xffffffff end
local function psx(p,n)assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'PSX pointer invalid');return p&amp;0x1fffff end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function binary(r,o,n)
 assert(o&gt;=0 and n&gt;=0 and o+n&lt;=0x200000,'Capture outside RAM')
 local out={}
 for j=0,n-1,4096 do local k=math.min(4096,n-j);local t=assert(readBytes(r+o+j,k,true));assert(#t==k);out[#out+1]=string.char(table.unpack(t))end
 return table.concat(out)
end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function isBranch(w)return op(w)==1 or (op(w)&gt;=4 and op(w)&lt;=7)or op(w)==2 or op(w)==3 or (op(w)==0 and ((w&amp;63)==8 or (w&amp;63)==9))end
local function copy(t)local r={};for k,v in pairs(t)do r[k]=v end;return r end
local function destination(w)
 if op(w)==0 then return rd(w)end
 if (op(w)&gt;=8 and op(w)&lt;=15)or (op(w)&gt;=32 and op(w)&lt;=39)then return rt(w)end
end
-- Conservative backwards slice: only a direct work-field load, a move and/or
-- a left shift are accepted. Branches, calls and complex arithmetic reject it.
local function expression(words,aliases,at,reg,depth)
 if (depth or 0)&gt;5 then return nil end
 if reg==0 then return {kind='constant',value=0}end
 for i=at,math.max(1,at-24),-1 do
  local w=words[i];if isBranch(w)then return nil end
  if destination(w)==reg then
   if op(w)==35 then
    local base=aliases[i][rs(w)]
    if base~=nil and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     local offset=base+signed(w&amp;0xffff)
     if offset&gt;=0x20 and offset&lt;=0x4000 and offset%4==0 then return {kind='field',offset=offset,scale=1}end
    end
   elseif op(w)==9 and rs(w)==0 then return {kind='constant',value=signed(w&amp;0xffff)}
   elseif op(w)==13 and rs(w)==0 then return {kind='constant',value=w&amp;0xffff}
   elseif op(w)==0 then
    local f=w&amp;63
    if (f==33 or f==37)and (rs(w)==0 or rt(w)==0)then
     return expression(words,aliases,i-1,rs(w)==0 and rt(w)or rs(w),(depth or 0)+1)
    elseif f==0 and rs(w)==0 then
     local e=expression(words,aliases,i-1,rt(w),(depth or 0)+1);local shift=(w&gt;&gt;6)&amp;31
     if e and shift&lt;=4 then if e.kind=='field'then e.scale=e.scale*(1&lt;&lt;shift)else e.value=e.value*(1&lt;&lt;shift)end;return e end
    end
   end
   return nil
  end
 end
end
function B.ownership(r,actor)
 assert(binary(r,0x2D410,48)==string.char(132,7,132,143,0,0,0,0,64,0,130,40,3,0,64,20,192,24,4,0,8,0,224,3,33,16,0,0,33,24,100,0,192,24,3,0,11,128,2,60,224,100,66,36,33,24,98,0),'Integral TARGET allocator/release code differs')
 assert(binary(r,0x2D4B0,16)==string.char(17,0,128,16,11,128,3,60,132,7,133,143,152,100,99,36),'Integral TARGET allocator/release code differs')

 local e={targets={},fields={},proofs={},functions=0,blocks={}}
 local overlay=binary(r,0xc0000,0xa0000)
 local queue={{fn=actor.die,base=0},{fn=actor.act,base=0}};local seen={}
 local function mark(field,kind,pc,w)
  if field&lt;0x20 or field&gt;0x4000 then return end
  local v=e.fields[field]or {};e.fields[field]=v;v[kind]={pc=pc,word=w}
 end
 while #queue&gt;0 and e.functions&lt;128 do
  local item=table.remove(queue,1);local fn,base=item.fn,item.base;local key=tostring(fn)..':'..tostring(base)
  if item.aliases then for reg=1,31 do if item.aliases[reg]~=nil then key=key..':'..reg..'='..item.aliases[reg]end end end
  if not seen[key]and fn&gt;=0x800c0000 and fn&lt;0x80160000 and fn%4==0 then
   seen[key]=true;e.functions=e.functions+1
   local offset=(fn&amp;0x1fffff)-0xc0000
   local code=overlay:sub(offset+1,offset+0x1000);local words,aliases={},{};local alias=item.aliases or {[4]=base};local loaded={};local stop=false
   for i=1,#code//4 do
    local w=string.unpack('&lt;I4',code,(i-1)*4+1);local pc=fn+(i-1)*4;words[i]=w;aliases[i]=copy(alias)
    local o=op(w);local field=alias[rs(w)]and alias[rs(w)]+signed(w&amp;0xffff)
    if field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     if o==35 then mark(field,'read',pc,w);loaded[rt(w)]={field=field}
     elseif o==43 then mark(field,'write',pc,w);if loaded[rt(w)]and loaded[rt(w)].field==field and loaded[rt(w)].decrement then mark(field,'decrement',pc,w)end end
    end
    if o==35 and not(field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23)))then loaded[rt(w)]=nil end
    local dest=destination(w);local value
    if o==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if rt(w)==0 then value=alias[rs(w)]elseif rs(w)==0 then value=alias[rt(w)]end
    elseif o==9 and alias[rs(w)]~=nil then value=alias[rs(w)]+signed(w&amp;0xffff)end
    if o==9 and rt(w)==rs(w)and signed(w&amp;0xffff)==-1 and loaded[rt(w)]then loaded[rt(w)].decrement=true
    elseif dest and dest~=0 and o~=35 then loaded[dest]=nil end
    if dest and dest~=0 then alias[dest]=value end
    local prior=words[i-1]
    if prior and (op(prior)==3 or op(prior)==2)then
     local callee=((prior&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if callee==0x8002d4b0 then
      local exp
      if destination(w)==4 then
       exp=expression({w},{aliases[i]},1,4)
       if not exp and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)and (rs(w)==0 or rt(w)==0)then exp=expression(words,aliases,i-2,rs(w)==0 and rt(w)or rs(w))end
      else exp=expression(words,aliases,i-2,4)end
      if exp and exp.kind=='field'and exp.scale==1 then e.targets[exp.offset]={field=exp.offset,pc=pc-4,word=prior}end
     elseif callee&gt;=0x800c0000 and callee&lt;0x80160000 then
      if op(prior)==2 then
       -- Follow a real unconditional control-flow edge, preserving its work
       -- aliases. Do not fall through into the next unrelated function.
       queue[#queue+1]={fn=callee,aliases=copy(alias)}
      elseif alias[4]and alias[4]&gt;=0 and alias[4]&lt;0x4000 then queue[#queue+1]={fn=callee,base=alias[4]}end
     end
     for j=2,15 do alias[j]=nil;loaded[j]=nil end;alias[24]=nil;alias[25]=nil
    end
    if stop then break end
    if o==2 or (o==0 and (w&amp;63)==8 and rs(w)==31)then stop=true end
   end
   e.blocks[#e.blocks+1]={address=r+(fn&amp;0x1fffff),bytes=code:sub(1,#words*4)}
  end
 end
 return e
end

return B
]====]):sub(2),
 [ [====[Integral/int-reader.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Master Collection Integral SLPM_862.47/.48, host build 20872173.
-- All target access in this module is read-only.
assert(process=='METAL GEAR SOLID.exe','Attach to METAL GEAR SOLID.exe')
assert(getModuleSize(process)==30007296,'Unsupported executable image size')
local base,pid=getAddress(process),getOpenedProcessID()
local R={pid=pid,module=base,vtable=base+0xab8cf0,version=1,variant='Integral JP'}
local function bytes(a,n)
 local b=assert(readBytes(a,n,true),'Memory unavailable')
 assert(#b==n,'Incomplete memory read');return b
end
local function fp(a,hex)
 local expected=hex:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)
 local b=bytes(a,#expected)
 assert(string.char(table.unpack(b))==expected,'Integral code/layout differs at '..string.format('%X',a))
end
fp(base+0x10b43d,'488D05ACD89A00')
fp(base+0x10b447,'41B900400800')
local function validate(ram)
 assert(ram and ram&gt;0x10000,'Emulated RAM missing')
 assert(readString(ram+0x10000,11)=='SLPM_862.48' and readString(ram+0x1000C,11)=='SLPM_862.47','Only captured Integral SLPM_862.47/.48 is supported')
 fp(ram+0x4FFE4,'0B80023CAE4D428400000000')
 fp(ram+0x2E948,'0B80043C00BA848C')
 fp(ram+0x2EA2C,'0B80033C18BA638C')
end
function R.checkFeature(kind)
 local ram=R.ram;validate(ram)
 if kind=='health'then
 fp(ram+0x4F2B8,'AD38010C8000043C9C08038E240A11A2000062940000000069FF4230000062A4')
 fp(ram+0x4E2B4,'0B80023C50BA428C00000000251044000B80013C50BA22AC0800E00300000000')
 fp(ram+0x4F310,'9C08038E0000000000006294000000009E004234000062A4')
 fp(ram+0x4F8B0,'212020029C08828C0001053C260046A40B80023C220A86A4BD38010CAE4D46A4')
 elseif kind=='ammo'then
 fp(ram+0x65A58,'0B80023CBA4D43940C0004240B80013CECB930A40B80013C2CBA24A4FFFF6324BA4D43A4')
 elseif kind=='inventory'then
 fp(ram+0x513A0,'0B80023C984D52241C004286040080121C0902AE')
 fp(ram+0x51768,'0B80023C984D52241E0042860400A012A80922AE')
 else error('Unsupported Integral feature')end
end
local pattern={}
for i=0,7 do pattern[#pattern+1]=string.format('%02X',(R.vtable&gt;&gt;(i*8))&amp;255)end
local found=AOBScan(table.concat(pattern,' '),'+W-C',fsmAligned,'8')
local candidates={}
if found then
 for i=0,found.Count-1 do
  local owner=tonumber(found[i],16);local ram=readQword(owner+0x28)
  if pcall(validate,ram)then candidates[#candidates+1]={owner=owner,ram=ram}end
 end
 found.destroy()
end
assert(#candidates==1,'Expected one validated Integral RAM owner; found '..#candidates)
R.owner,R.ram=candidates[1].owner,candidates[1].ram
local function u16(b,o)return b[o+1]|(b[o+2]&lt;&lt;8)end
local function s16(b,o)local n=u16(b,o);return n&gt;=32768 and n-65536 or n end
local function u32(b,o)return u16(b,o)|(u16(b,o+2)&lt;&lt;16)end
R.weapons={'SOCOM','FAMAS','Grenade','Nikita','Stinger','Claymore','C4','Stun grenade','Chaff grenade','PSG1'}
R.modes={[0]='NORMAL',[1]='JAMMING',[2]='EVASION',[3]='ALERT',[4]='SCRIPTED',[10]='TORTURE'}
function R.read()
 assert(getOpenedProcessID()==pid and process=='METAL GEAR SOLID.exe','Process changed; reload Integral controls')
 assert(readQword(R.owner)==R.vtable,'Emulator owner changed')
 local ram=readQword(R.owner+0x28)
 -- Game selection can replace the guest inside the SAME allocation.
 validate(ram);R.ram=ram
 local stage=readString(ram+0xb4d88,16)
 assert(stage and stage:match('^[%w_]+$')and #stage&lt;=12,'Enter Integral gameplay')
 local q,g=bytes(ram+0xb4d98,192),bytes(ram+0xab9e8,0x50)
 local h={pid=pid,ram=ram,stage=stage,health=s16(q,0x16),maximum=s16(q,0x18),
  weapon=s16(q,0x1c),item=s16(q,0x1e),magazine=s16(g,4),magazineMax=s16(g,0x44),
  alertMode=u32(g,0x18),alertLevel=u32(g,0x30),ration=s16(q,0x64),rationMax=s16(q,0x7a),ammo={},ammoMax={}}
 assert(h.maximum&gt;=1 and h.maximum&lt;=2000 and h.health&gt;=0 and h.health&lt;=h.maximum,'Health layout invalid')
 assert(h.weapon&gt;=-1 and h.weapon&lt;=9 and h.item&gt;=-1 and h.item&lt;=23,'Equipment layout invalid')
 assert(R.modes[h.alertMode]and h.alertLevel&lt;=65535,'Alert layout invalid')
 for i=1,10 do h.ammo[i]=s16(q,0x22+(i-1)*2);h.ammoMax[i]=s16(q,0x36+(i-1)*2)end
 h.weaponName=h.weapon==-1 and 'None'or R.weapons[h.weapon+1]
 h.ammoSelected=h.weapon&gt;=0 and h.ammo[h.weapon+1]or nil
 h.ammoSelectedMax=h.weapon&gt;=0 and h.ammoMax[h.weapon+1]or nil
 h.alertName=R.modes[h.alertMode]
 return h
end
INTReader=R
return R
]====]):sub(2),
 [ [====[Integral/int-room-catalog.lua]====] ]=([====[!-- Generated by analysis/build-integral-rooms.py.
-- Stage names: https://github.com/FoxdieTeam/mgs_reversing
return {
 {id=[==[s00a]==],name=[==[Loading Dock]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-5756,y=1104,z=-1298}},
 {id=[==[s01a]==],name=[==[Heliport]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-1722,y=1104,z=21437}},
 {id=[==[s02a]==],name=[==[Tank Hangar]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6000,y=1104,z=0}},
 {id=[==[s02b]==],name=[==[Tank Hangar]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=0,y=1104,z=10500}},
 {id=[==[s02c]==],name=[==[Tank Hangar (Before Contacting Meryl)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=0,y=1104,z=10500}},
 {id=[==[s02d]==],name=[==[Tank Hangar (After Contacting Meryl)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=3497,y=1104,z=7647}},
 {id=[==[s02e]==],name=[==[Tank Hangar (After Torture)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=3655,y=1049,z=8345}},
 {id=[==[s03a]==],name=[==[Holding Cell]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=1500,y=1104,z=1000}},
 {id=[==[s03ar]==],name=[==[Holding Cell (RED)]==],group=[==[Scenes / variants]==],note=[==[Tested variant stalled at a black screen with a frozen native frame counter. No placement accepted. Restart Integral and reload a save if it does not recover.]==],tested_load=false},
 {id=[==[s03b]==],name=[==[Medical Room]==],group=[==[Story rooms]==],note=[==[Torture room; special actor availability depends on story state. Earlier torture health protection was player-confirmed. This audit save loaded an empty advancing scene with radar hidden; guarded return succeeded. No normal floor preset is claimed.]==],tested_load=false},
 {id=[==[s03c]==],name=[==[Medical Room]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation. This scenario forces its own prison-cell entry and may use shirtless Snake; requested coordinates do not bypass cell/story restrictions.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=1500,y=1104,z=1000}},
 {id=[==[s03d]==],name=[==[Holding Cell]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s03dr]==],name=[==[Holding Cell (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s03e]==],name=[==[Holding Cell (vs. Soldiers)]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],encounter=[==[Soldier ambush]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s03er]==],name=[==[Holding Cell (vs. Soldiers) (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s04a]==],name=[==[Armory]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=3655,y=1049,z=8345}},
 {id=[==[s04b]==],name=[==[Armory South (vs. Ocelot)]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],encounter=[==[Revolver Ocelot]==],tested_load=true,spawn_verified=true,map=49736,spawn={x=-2004,y=1104,z=10163}},
 {id=[==[s04br]==],name=[==[Armory South (vs. Ocelot) (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=49736,spawn={x=-2004,y=1104,z=10163}},
 {id=[==[s04c]==],name=[==[Armory South]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=3655,y=1104,z=8345}},
 {id=[==[s05a]==],name=[==[Canyon]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],encounter=[==[Tank / Raven]==],tested_load=true,spawn_verified=true,map=65,spawn={x=-6617,y=104,z=-12760}},
 {id=[==[s06a]==],name=[==[Warhead Storage Building 1F]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6617,y=1104,z=-12760}},
 {id=[==[s07a]==],name=[==[Warhead Storage Building B1]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6954,y=1104,z=-12760}},
 {id=[==[s07b]==],name=[==[Commander's Room]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],encounter=[==[Psycho Mantis]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-670,y=1104,z=875}},
 {id=[==[s07br]==],name=[==[Commander's Room (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-670,y=1104,z=875}},
 {id=[==[s07c]==],name=[==[Warhead Storage Building B1]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6954,y=1104,z=-12760}},
 {id=[==[s07cr]==],name=[==[Warhead Storage Building B1 (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6954,y=1104,z=-12760}},
 {id=[==[s08a]==],name=[==[Warhead Storage Building B2]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=750,y=1104,z=-750}},
 {id=[==[s08b]==],name=[==[Laboratory]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],encounter=[==[Cyborg Ninja]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6378,y=1049,z=55}},
 {id=[==[s08br]==],name=[==[Laboratory (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6378,y=1049,z=55}},
 {id=[==[s08c]==],name=[==[Corridor]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=951,y=1104,z=-750}},
 {id=[==[s08cr]==],name=[==[Corridor (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=951,y=1104,z=-750}},
 {id=[==[s09a]==],name=[==[Caves]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6000,y=1104,z=11000}},
 {id=[==[s09ar]==],name=[==[Caves (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-6000,y=1104,z=11000}},
 {id=[==[s10a]==],name=[==[Underground Passage]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation. Equip PSG1 before approaching Wolf; without it the game can force retreat.]==],encounter=[==[Sniper Wolf - first fight]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-1286,y=-28896,z=21681}},
 {id=[==[s10ar]==],name=[==[Underground Passage (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-1286,y=-28896,z=21681}},
 {id=[==[s11a]==],name=[==[Communication Tower A]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=43477,spawn={x=4000,y=1104,z=-5500}},
 {id=[==[s11b]==],name=[==[Communication Tower Roof]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-3827,y=1104,z=22054}},
 {id=[==[s11c]==],name=[==[Communication Tower B]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=61936,spawn={x=-4000,y=-10896,z=-5500}},
 {id=[==[s11d]==],name=[==[Communication Tower A Wall]==],group=[==[Story rooms]==],note=[==[Loads the special rappelling actor, not a walking-floor preset. One player-completed descent to s11i was verified on 2026-11-21 with private health protection active and normal invulnerability resuming afterward. Normal room loading is unavailable until the rope sequence ends.]==],tested_load=true,sequence_verified=true,sequence_exit=[==[s11i]==]},
 {id=[==[s11e]==],name=[==[Communication Tower B Elevator]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=500,y=1104,z=625}},
 {id=[==[s11g]==],name=[==[Communication Tower B Roof]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation. Verified landing beside the roof ladder after a short entry scene. Some earlier story states loaded no Snake; central roof combat placement is not claimed.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-3827,y=1104,z=22054}},
 {id=[==[s11h]==],name=[==[Communication Tower B Roof (vs. Hind D)]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation. This scenario forces the roof-approach landing beside the ladder, rather than the requested central coordinates. A central combat spawn remains unverified.]==],encounter=[==[Hind D]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s11i]==],name=[==[Communication Tower Walkway]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=6000,y=-15396,z=0}},
 {id=[==[s12a]==],name=[==[Snowfield]==],group=[==[Encounters]==],note=[==[Snowfield entry was initially movable but later locked input in this save, even with PSG1 owned. No persistent spawn preset accepted. Previous-room recovery supports the observed normal-Snake input lock and returns only to the verified source; health protection can remain on.]==],encounter=[==[Sniper Wolf - second fight]==],tested_load=false},
 {id=[==[s12b]==],name=[==[Snowfield (After vs. Sniper Wolf)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-3682,y=2604,z=-19273}},
 {id=[==[s12c]==],name=[==[Snowfield (After vs. Sniper Wolf)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-3682,y=2604,z=-19273}},
 {id=[==[s13a]==],name=[==[Blast Furnace]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-3682,y=1104,z=-19047}},
 {id=[==[s14e]==],name=[==[Cargo Elevator]==],group=[==[Story rooms]==],note=[==[Uses the game's normal room load. Entry position and active actors depend on story progress. This tested story state loaded an empty scene without Snake; playable placement remains unverified.]==],tested_load=false},
 {id=[==[s15a]==],name=[==[Warehouse]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation. Initial entry displayed s2000a0.dmo. After normal confirmation, preset reload placed Snake on visible floor0 with the Raven bar present. Encounter outcome remains untested.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=0,y=1104,z=-2000}},
 {id=[==[s15b]==],name=[==[Warehouse North]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s15c]==],name=[==[Warehouse]==],group=[==[Encounters]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation. The initial entry can show unavailable demo s2000a0.dmo; dismiss with Circle/confirm. Preset reload and interior floor placement were verified after dismissal.]==],encounter=[==[Vulcan Raven]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s16a]==],name=[==[Underground Base (1F)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s16b]==],name=[==[Underground Base (2F)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-18. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=-750,y=-2896,z=3119}},
 {id=[==[s16c]==],name=[==[Underground Base (3F)]==],group=[==[Story rooms]==],note=[==[Current native entry drops Snake below the visible catwalks. Collision-only trial points did not produce a visually verified placement; no corrected preset is shipped.]==],tested_load=false},
 {id=[==[s16d]==],name=[==[Underground Base (Control Room)]==],group=[==[Story rooms]==],note=[==[Scripted control-room sequence. Dismiss s2105a0.dmo normally and finish Otacon's conversation. In the tested save it automatically returns to normal Snake on the s16c catwalk; confirmed by the player and live floor/visual checks. This is a sequence route, not a stationary room spawn.]==],tested_load=true,sequence_verified=true,sequence_exit=[==[s16c]==]},
 {id=[==[s17a]==],name=[==[Supply Route (vs. REX)]==],group=[==[Encounters]==],note=[==[Loads the arena; encounter availability depends on your current story progress.]==],encounter=[==[Metal Gear REX]==],tested_load=false},
 {id=[==[s17ar]==],name=[==[Supply Route (vs. REX) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.]==],tested_load=false},
 {id=[==[s18a]==],name=[==[Supply Route (vs. Liquid)]==],group=[==[Encounters]==],note=[==[Loads the arena; encounter availability depends on your current story progress.]==],encounter=[==[Liquid Snake - rooftop]==],tested_load=false},
 {id=[==[s18ar]==],name=[==[Supply Route (vs. Liquid) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.]==],tested_load=false},
 {id=[==[s19a]==],name=[==[Escape Route (Garage)]==],group=[==[Story rooms]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation. A short Meryl entry scene plays before normal Snake returns; the escape countdown runs.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=15500,y=-396,z=-3000}},
 {id=[==[s19ar]==],name=[==[Escape Route (Garage) (RED)]==],group=[==[Scenes / variants]==],note=[==[Interior spawn checked by native reload, collision support and visible textured ground on 2026-11-21. Story state determines encounter availability; movement needs player confirmation.]==],tested_load=true,spawn_verified=true,map=32249,spawn={x=15500,y=-396,z=-3000}},
 {id=[==[s19b]==],name=[==[Escape Route (Tunnel)]==],group=[==[Encounters]==],note=[==[Observed Snake on the jeep in the tunnel. Vehicle actor requires separate placement validation and is not a normal walking spawn. Integral health protection includes jeep health refill; normal room loading remains unavailable while using the vehicle actor.]==],encounter=[==[Liquid Snake - escape]==],tested_load=false},
 {id=[==[s19br]==],name=[==[Escape Route (Tunnel) (RED)]==],group=[==[Scenes / variants]==],note=[==[Player confirmed the jeep escape reached end-game credits on 2026-11-22 with main health protection enabled; live reader confirmed credits stage roll and HP576. Vehicle sequence route, not a walking-ground preset. Guarded jeep refill supports this variant; full normal on-foot loading is unavailable while riding.]==],tested_load=true,sequence_verified=true,sequence_exit=[==[roll]==]},
 {id=[==[s20a]==],name=[==[Ending Demo (SCENE 28-1)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.]==],tested_load=false},
 {id=[==[s20ar]==],name=[==[Ending Demo (SCENE 28-1) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.]==],tested_load=false}
}
]====]):sub(2),
 [ [====[Integral/int-room-loader.lua]====] ]=([====[!-- Generated by analysis/build-integral-rooms.py.
-- One-shot native Integral room loads. Opening the dashboard never loads a room.
local prior=INTRoomLoader
if prior and prior.pid==getOpenedProcessID()and prior.version==7 then return prior end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local G=dofile(dir..'int-inventory.lua')
local W={pid=R.pid,version=7,catalog=dofile(dir..'int-room-catalog.lua'),history={},status='Choose a destination. Loading begins only when you click Load.'}
if prior and prior.pid==W.pid then
 for _,key in ipairs({'history','pending','previous','last','status'})do W[key]=prior[key]end
end
local byID={};for _,e in ipairs(W.catalog)do assert(not byID[e.id],'Duplicate destination');byID[e.id]=e end
local function u16(a)return assert(readSmallInteger(a),'Area read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Area read unavailable')&amp;0xFFFFFFFF end
local function value(r,v)return v.size==1 and assert(readBytes(r+v.offset,1))or v.size==2 and u16(r+v.offset)or u32(r+v.offset)end
local function hash(s)local n=0;for i=1,#s do n=(((n&lt;&lt;5)|(n&gt;&gt;11))+s:byte(i))&amp;0xFFFF end;return n end
local function fingerprint(r)
 for _,p in ipairs(W.proofs)do
  local bytes=assert(readBytes(r+p.offset,#p.bytes,true),'Native loader unavailable')
  assert(#bytes==#p.bytes,'Incomplete native loader read')
  for i=1,#p.bytes do assert(bytes[i]==p.bytes:byte(i),'Integral native stage-loader code differs')end
 end
end
function W.destination(id)
 assert(type(id)=='string'and #id&lt;=7 and id:match('^s%d%d%lr?$'),'Select a catalog destination')
 return assert(byID[id],'Destination is not in the Integral stage catalog')
end
function W.context(recoveryID)
 assert(getOpenedProcessID()==W.pid,'Attached process changed; reopen the dashboard')
 local c
 if recoveryID then
  -- Empty idle scene, or the observed s12a pad-release lock on normal Snake.
  -- The only allowed target is the verified room this exact request left.
  local h=R.read();local r=h.ram;local last=assert(W.last,'No preceding room request')
  local target=W.destination(recoveryID)
  assert(last.state=='arrived'and last.to==h.stage and last.from==recoveryID and last.ram==r,'Recovery must return from the last confirmed load')
  assert(target.spawn_verified and target.spawn and target.map~=nil,'Return room needs a verified interior preset')
  assert(getTickCount()-last.started&gt;=5000,'Wait for the scene to settle')
  assert(h.health&gt;0 and u32(r+0xAB3D0)==0 and u32(r+0xABA38)~=0 and u32(r+0xAB3D4)==0,'Recovery requires a loaded living state')
  local flags=u32(r+0xAB3CC);local player=u32(r+0xABA50)
  -- STATE_RADAR_OFF affects display only; other empty-scene flags refuse.
  local empty=flags&amp;(~0x400000&amp;0xFFFFFFFF)==0 and player==0 and u32(r+0xAB9F4)==0 and u32(r+0xABA20)==0
  if empty then c={ram=r,stage=h.stage,h=h}
  -- BEGIN Integral-only Snowfield recovery
  elseif h.stage=='s12a'and flags==0x10000100 and player&amp;(~0x800040&amp;0xFFFFFFFF)==0 then
   -- Return to the verified source without clearing input or story flags.
   c=G.context(false);assert(c.ram==r and c.stage==h.stage,'Return actor binding changed')
  -- END Integral-only Snowfield recovery
  else error('Recovery requires an empty idle scene or the validated Snowfield input lock')end
 else c=G.context(true)end
 local r=c.ram;local current=hash(c.stage)
 assert(u32(r+0xAB928)==0,'Resume the game or dismiss its paused demo/message before loading')
 assert(u32(r+0xBD360+8)==0x800386A4 and u32(r+0xBD360+12)==0x800387E8 and u16(r+0xBD360+0x2A)==0,'Close the codec or equipment menu')
 assert(readString(r+0xAB3C4,8)==c.stage and u16(r+0xAB9C0)==current and u16(r+0xB4DA4)==current and u16(r+0xB5850)==current,'Wait for the current room transition to finish')
 return c
end
function W.plan(id,recovery)
 assert(recovery==nil or type(recovery)=='boolean','Invalid recovery mode')
 local destination=W.destination(id)
 local map=destination.map
 if map~=nil then assert(type(map)=='number'and map%1==0 and map&gt;=0 and map&lt;=0xFFFF,'Invalid room entry map')end
 local spawn
 if destination.spawn then
  spawn={}
  for _,axis in ipairs({'x','y','z'})do
   local n=destination.spawn[axis]
   assert(type(n)=='number'and n%1==0 and n&gt;=-32768 and n&lt;=32767,'Invalid room entry coordinate')
   spawn[axis]=n
  end
 end
 assert(not W.pending,'A room load is already pending')
 local c=W.context(recovery and id or nil);local r=c.ram;fingerprint(r)
 local current=hash(c.stage);local target=hash(id);local writes={}
 local function add(offset,size,new)
  local v={offset=offset,size=size,value=new};v.before=value(r,v);writes[#writes+1]=v
 end
 -- GM_SetArea: shift history, publish area hash and eight-byte name.
 for i=7,1,-1 do add(0xB5850+i*2,2,u16(r+0xB5850+(i-1)*2))end
 add(0xB5850,2,target);add(0xAB9C0,2,target)
 local name=id..string.rep('\0',8-#id)
 for i=1,8 do add(0xAB3C4+i-1,1,name:byte(i))end
 -- Ordinary LoadCmd: previous/current area, then default request last.
 -- Only a recorded destination preset supplies the native LoadCmd p: vector.
 -- A recorded m: selector chooses the native sub-map. Inventory, story flags and disk are untouched.
 add(0xB4E2C,2,current);add(0xB4DA4,2,target)
 if map~=nil then add(0xB4DA6,2,map)end
 if spawn then
  add(0xB4DA8,2,spawn.x&amp;0xFFFF);add(0xB4DAA,2,spawn.y&amp;0xFFFF);add(0xB4DAC,2,spawn.z&amp;0xFFFF)
 end
 add(0xAB3D0,4,0x11)
 return {pid=W.pid,ram=r,from=c.stage,to=id,destination=destination,spawn=spawn,map=map,recovery=not not recovery,writes=writes}
end
function W.request(id,recovery)
 local p=W.plan(id,recovery);local c=W.context(recovery and id or nil)
 assert(c.ram==p.ram and c.stage==p.from,'Area changed before load; try again')
 fingerprint(c.ram)
 for _,v in ipairs(p.writes)do assert(value(c.ram,v)==v.before,'Area state changed before load; try again')end
 assert(getOpenedProcessID()==p.pid and readQword(R.owner+0x28)==p.ram,'Process or RAM owner changed before load')
 local written=0
 for _,v in ipairs(p.writes)do
  local a=c.ram+v.offset;local ok
  if v.size==1 then ok=writeBytes(a,v.value)elseif v.size==2 then ok=writeSmallInteger(a,v.value)else ok=writeInteger(a,v.value)end
  if not ok then W.status='Load failed after '..written..' writes. No automatic retry.';error(W.status)end
  written=written+1
 end
 local action={from=p.from,to=p.to,ram=p.ram,spawn=p.spawn,map=p.map,recovery=p.recovery,started=getTickCount(),state='requested',writes=written}
 W.pending=action;W.last=action;W.history[#W.history+1]=action
 if #W.history&gt;20 then table.remove(W.history,1)end
 W.status='Load requested: '..p.from..' -&gt; '..p.to..'. Return to the game while it loads.'
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/integral-room-loads.csv','a+'))
  local good,why=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,pid,from,to,request\n'))end
   assert(f:write(string.format('%s,%d,%s,%s,0x11\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),W.pid,p.from,p.to)))
  end)
  f:close();assert(good,why)
 end)
 if not ok then W.logError=tostring(err)end
 return action
end
function W.poll()
 assert(getOpenedProcessID()==W.pid,'Attached process changed; reopen the dashboard')
 local h=R.read();local r=h.ram;local p=W.pending
 if p then
  if r~=p.ram then
   p.state='unconfirmed';W.pending=nil;W.status='RAM changed; load result unconfirmed. No automatic retry.'
  elseif h.stage==p.to and readString(r+0xAB3C4,8)==p.to and u32(r+0xAB3D0)==0 and u32(r+0xABA38)~=0 then
   p.state='arrived';W.pending=nil;W.previous=p.from
   W.status='Loaded '..p.to..'. Story progress determines actors, encounters and entry position.'
  elseif getTickCount()-p.started&gt;30000 then
   p.state='unconfirmed';W.pending=nil
   W.status='Load not confirmed within 30 seconds. Return to the game and check its screen; no automatic retry.'
  end
 end
 local ok,c=pcall(W.context)
 local canRecover=false
 if not ok and not W.pending and W.last then canRecover=pcall(W.context,W.last.from)end
 return {stage=h.stage,health=h.health,maximum=h.maximum,ready=ok and not W.pending,reason=not ok and tostring(c)or W.pending and 'Room load pending'or nil,
         nativeStage=readString(r+0xAB3C4,8),previous=W.previous,pending=W.pending,canRecover=canRecover}
end
function W.returnPrevious()
 assert(W.previous,'No previous room recorded in this dashboard session')
 return W.request(W.previous)
end
function W.recoverPrevious()
 assert(W.last,'No preceding room request')
 return W.request(W.last.from,true)
end
W.proofs={{offset=0x2C308,bytes=('d8ffbd272000bfaf1c00b1afa982000c1800b0af9c82000c2120400021804000000002920000000055004010010002245a82000c720004241d0040100b80023cb582000c00000000120040140b80023c20aa000c212000020b80043c58ba8424da39020c21284000ec58000c000000001655000c00000000c476000c00000000335b000c2120000221204000eab0000821280002a44d44840b80053c58baa524f6a9000c0000000022b1000801000224984d51240c00229621200002335b000c940022a6002402000324040021280002f6a9000c0c0022a65a82000c6d0004240400401000000000b582000c000000000e0022a65a82000c700004240c00401000000000a982000c00000000212040008582000c1000a5271000a2971200a3971400a497100022a6120023a6140024a65a82000c730004240700401001000224b582000c000000000b80013cd0b322ac03004010800042340b80013cd0b322ac5a82000c6e00042408004014211000000b80023cd0b3428c00000000100042340b80013cd0b322ac211000002000bf8f1c00b18f1800b08f0800e0032800bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x2A7D8,bytes=('e8ffbd271000b0af218080000b80043cc4b384241400bfafdc0690a7da39020c00000000070004240b80023c5058452440180400ffff82242120400040100400211045000000429421186500f8ff801c000062a40b80023c505850a4211000021400bf8f1000b08f0800e0031800bd27010003240b80023c50584224020045240000a2840000000005004410000000000100632408006228f9ff40140200a5240800e003211060000b80023cc4b342240800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x2ADBC,bytes=('c0ffbd273000b0af21808000010004243c00bfaf3800b2af9730020c3400b1af010004242f31020c2190400001000324050043140b80033c984d63240400629485ab0008fffb4230984d6324040062940000000000044234040062a40b80023c9c4d4294000000000024423012004014000000005807828f00000000030040100100042493ab00080a000524212800000231020c000000007007858f000000000001a2280200401400000000ff0005241531020c010004240b80023c28b9428c700780af580780af0800423013004010000000000c80023cf0ef428c000000000a00401400000000228a000c000000000300032405004310f7ff03240b80023c28b9428cc4ab00082410430027ab000c00000000c6ab0008000000000c80023cf0ef428c000000000600401400000000228a000c000000000300032407004314000000000b80023c28b9428c00000000080042340b80013c28b922ac0b80023c28b9428c00000000020042301f0040148888043c0407838f0b80023c24b9428c898884342118620018006400a291053cc5b3a534c31703001040000021200301432104002320820018008500040783af0b80053c984da524c31704001040000021180401c31a030023186200c01003002310430040110200211043000011020023208200b600a3a4b800a4a42000118e000000000500201201000224400022120000000050ad0008000000005407828f000000005b01401001000324ec00828f540783af8000423003004010000000000b80013c80b320ac0b80023c9452428c0000000005004010000000002155000c00000000c876000c0000000028c4000c00000000a8c1000c000000000a7f000c0000000035ba000c00000000ec00828f00000000100042300300401000000000c584000c000000000180043ce82e020cac0a8424ec00848fec0080af200082300500401002240400cb7f000c2128000024ac00080180043c8a80000c000000000180043ce82e020cbc0a842480e2000c00000000aeba000c0000000090b9000c000000000100022450ad0008200002ae2400028e00000000e900401cf7ff0224f000828f0000000021004010000000006b0040180f0943321a005114ffff422436df000c0000000021804000ffff02240c00021600000000bedd000c01000424040040100f094332f00090afa4ac00080f0902240454000c04000424a3ac00080f09433236df000c00000000540051140f09433259df000c00000000a3ac00080f094332f00082afa3ac00080f094332ec00838f0000000020006010000000000b80023c28b9428c00000000020042301a0040148000623003004010ff7f023c0b80013c80b322ac0454000c040004240b80023c28b9428cf7ff0324241043000b80013c28b922ac0ac4000c0000000059df000c000000004a10043c00608434e800828f03000324240003ae25104400e80082af50ad0008000000000b80023c28b9428c000000000400401400d8033c47ba000c0000000000d8033ce800828f204063342410430012004014fdff03240b80023c28b9428c000000002410430014004014000000003806828f000000000200429400000000000842300d00401000000000e9aa000c00000000a0ac0008000000000b80023c28b9428c00000000020042300300401000000000bbaa000c00000000e9c3000c000000000f0943320f090224430062145a0002241001828f000000003f0040145a000224ec06828f00000000ffff4224ec0682af3a0041040b80043c605884240180053ccc0aa5240180113c0a80033c0b80023cf0cb428cfcd2632480100200211043000000468c1e3a020c218080004b65020c00000000f33d020c212000009368020c000000005a51020c000000008231020c000000008a5a020c21200000112c020c000000003194000c000000003a3d020c030004240361020c0000000010000424040005241f80063cef65020cf0ffc634c660020c000000000361020c000000000d65020c000000000765020c00000000dc0a2426e82e020c21280002212000021f80053c00ffa5340365020c21300000dfac0008dc0a2426ec0682afe800828f000000000a004104000000003806828f00000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
INTRoomLoader=W
return W
]====]):sub(2),
 [ [====[Integral/int-stats.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- One-shot edits to confirmed PSX link-variable statistics and the real clock.
if INTStats and INTStats.pid==getOpenedProcessID()then return INTStats end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local S={pid=R.pid,reader=R,version=1,status='Read-only until you press Apply.'}
S.fields={
 {key='alerts',name='Alerts / times found',index=78},
 {key='kills',name='Enemies killed',index=79},
 {key='saves',name='Saves',index=88},
 {key='continues',name='Continues',index=87},
 {key='rations',name='Rations used',index=86},
 {key='pitfalls',name='Pitfall deaths',index=80},
 {key='mice',name='Mice killed',index=81},
 {key='crows',name='Crows killed',index=82},
}
local levels={[-1]='Very easy',[0]='Easy',[1]='Normal',[2]='Hard',[3]='Extreme'}
local function u16(a)return assert(readSmallInteger(a),'Statistic unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Game state unavailable')&amp;0xffffffff end
local function integer(v,minimum,maximum,name)
 v=tonumber(v)
 assert(v and v==math.floor(v)and v&gt;=minimum and v&lt;=maximum,(name or 'Value')..' must be a whole number from '..minimum..' to '..maximum..'.')
 return v
end
local function fp(ram,offset,expected)
 local b=assert(readBytes(ram+offset,#expected,true),'Statistics code unavailable')
 for i,v in ipairs(expected)do assert(b[i]==v,'Statistics code/layout differs.')end
end
function S.context(writing)
 local h=R.read();local r=h.ram
 assert(u32(r+0xab3d0)==0 and u32(r+0xaba38)~=0,'Wait for area loading to finish.')
 local control=u32(r+0xab9f4)
 assert(control&gt;=0x80000020 and control&lt;0x80200000,'Wait for normal gameplay.')
 local work=(control&amp;0x1fffff)-0x20
 assert(work+0xa28&lt;0x200000 and u32(r+work+8)==0x8005ad10 and u32(r+work+12)==0x8005b52c,'Snake actor differs.')
 assert(u32(r+0xaba20)==0x80000000+work+0x9c,'Snake body ownership differs.')
 local ready=h.health&gt;0 and u32(r+0xab3d4)==0 and u32(r+0xab3cc)&amp;0xd40c0000==0 and u32(r+0xaba50)&amp;0x20002084==0
 if writing then
  assert(ready,'Finish the cutscene or restricted action first.')
  assert(u32(r+0xAB928)==0,'Resume gameplay before applying statistics.')
  assert(u32(r+0xBD368)==0x800386A4 and u32(r+0xBD36C)==0x800387E8 and u16(r+0xBD38A)==0,'Close the codec or equipment menu.')
  -- Save live linkvars B4D98, checkpoint copy B44C8; hours/seconds indices91/92.
  fp(r,0x20C40,{11,128,2,60,152,77,66,36,11,128,5,60,11,128,3,60,232,185,99,140,136,77,165,36,8,0,35,174,182,0,67,148,184,0,70,148,11,128,16,60,186,0,67,164,188,0,70,164,176,0,66,148,200,68,16,38,186,0,3,166,188,0,6,166,176,0,2,166})
  fp(r,0x2AF30,{4,7,131,143,11,128,2,60,36,185,66,140,137,136,132,52,33,24,98,0})
  fp(r,0x2AF68,{4,7,131,175,11,128,5,60,152,77,165,36,195,23,4,0})
  fp(r,0x2AFA0,{182,0,163,164,184,0,164,164})
 end
 return {ram=r,h=h,work=work,ready=ready,stage=readString(r+0xb4d88,16)or '?'}
end
function S.inspect()
 local c=S.context(false);local r=c.ram;c.values={}
 for _,e in ipairs(S.fields)do c.values[e.key]=u16(r+0xb4d98+e.index*2)end
 c.hours=u16(r+0xb4e4e);c.seconds=u16(r+0xb4e50);c.frames=u32(r+0xab9e8)
 c.playTime=S.formatTime(c.hours,c.seconds)
 c.stageTime=S.formatTime(u16(r+0xb4e4a),u16(r+0xb4e4c))
 c.lastSaveTime=S.formatTime(u16(r+0xb4e52),u16(r+0xb4e54))
 local level=u16(r+0xb4d9a);if level&gt;=32768 then level=level-65536 end
 c.difficulty=levels[level]or ('Unknown ('..level..')')
 return c
end
function S.formatTime(hours,seconds)
 hours=hours+math.floor(seconds/3600);seconds=seconds%3600
 return string.format('%02d:%02d:%02d',hours,math.floor(seconds/60),seconds%60)
end
local function log(c,key,before,after,savedBefore,savedAfter)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/integral-statistics-edits-'..S.pid..'.csv','a+'))
  local success,problem=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,stage,field,before,after,saved_before,saved_after\n'))end
   assert(f:write(table.concat({os.date('!%Y-%m-%dT%H:%M:%SZ'),c.stage,key,before,after,savedBefore,savedAfter},',')..'\n'))
  end)
  f:close();assert(success,problem)
 end)
 if not ok then S.logError=tostring(err)end
end
function S.setCounter(key,value)
 local e
 for _,f in ipairs(S.fields)do if f.key==key then e=f;break end end
 assert(e,'Unknown statistic.')
 value=integer(value,0,32767,e.name)
 local c=S.context(true);local a=c.ram+0xb4d98+e.index*2;local before=u16(a)
 local saved=c.ram+0xb44c8+e.index*2;local savedBefore=u16(saved)
 local fresh=S.context(true);assert(fresh.ram==c.ram and fresh.work==c.work and fresh.stage==c.stage,'Game changed before statistics edit')
 assert(writeSmallInteger(a,value),'Statistic write failed.')
 assert(writeSmallInteger(saved,value),'Saved statistic write failed.')
 local actual=u16(a);assert(actual==value,'Game changed the counter during the edit; refresh and try again.')
 assert(u16(saved)==value,'Saved statistic did not retain the edit.')
 S.status=e.name..': '..before..' -&gt; '..actual..'. Normal tracking continues.'
 log(c,key,before,actual,savedBefore,u16(saved));return actual
end
function S.setTime(hours,minutes,seconds)
 hours=integer(hours,0,9942,'Hours');minutes=integer(minutes,0,59,'Minutes');seconds=integer(seconds,0,59,'Seconds')
 local total=hours*3600+minutes*60+seconds
 assert(total&lt;=math.floor(0x7fffffff/60),'Play time exceeds the signed game-clock limit.')
 local c=S.context(true);local r=c.ram;local oldFrames=u32(r+0xab9e8)
 local savedBefore=S.formatTime(u16(r+0xb457e),u16(r+0xb4580))
 -- Integral's gp+704 accumulator is AB9E8; synchronize live/save clock slots.
 local fresh=S.context(true);assert(fresh.ram==c.ram and fresh.work==c.work and fresh.stage==c.stage,'Game changed before clock edit')
 assert(writeInteger(r+0xab9e8,total*60),'Game-clock write failed.')
 assert(writeSmallInteger(r+0xb4e4e,hours),'Play-time hours write failed.')
 assert(writeSmallInteger(r+0xb4e50,minutes*60+seconds),'Play-time seconds write failed.')
 assert(writeSmallInteger(r+0xb457e,hours),'Saved play-time hours write failed.')
 assert(writeSmallInteger(r+0xb4580,minutes*60+seconds),'Saved play-time seconds write failed.')
 local now=u32(r+0xab9e8)
 assert(now&gt;=total*60 and now-total*60&lt;=600,'Clock changed unexpectedly during the edit; refresh and try again.')
 local before=S.formatTime(math.floor(oldFrames/216000),math.floor(oldFrames/60)%3600)
 local after=S.formatTime(hours,minutes*60+seconds)
 S.status='Play time: '..before..' -&gt; '..after..'. Clock keeps running.'
 log(c,'play_time',before,after,savedBefore,S.formatTime(u16(r+0xb457e),u16(r+0xb4580)));return total
end
INTStats=S
return S
]====]):sub(2),
 [ [====[Integral/int-toggles.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Optional data-only cheats for the validated Integral layout.
-- No game code patches, injected calls or debugger attachment.
if INTToggles then
 assert(INTToggles.pid==getOpenedProcessID(),'Stop the old controller before changing processes')
 return INTToggles
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'int-reader.lua')end
local T={pid=R.pid,reader=R,version=5,health={enabled=false,requested=false,rebinds=0,status='OFF'},ammo={enabled=false,requested=false,rebinds=0,status='OFF'},stopped=false}
local INV=0x800000
local MASK=0x96
local function u16(address)return assert(readSmallInteger(address),'Cannot read 16-bit value')&amp;0xffff end
local function u32(address)return assert(readInteger(address),'Cannot read 32-bit value')&amp;0xffffffff end
local function put16(address,value,mask)
 assert(writeSmallInteger(address,value&amp;0xffff),'16-bit write failed')
 if mask~=false then
  mask=mask or 0xffff
  assert(u16(address)&amp;mask==(value&amp;mask),'16-bit verification failed')
 end
end
local function put32(address,value,mask)
 assert(writeInteger(address,value&amp;0xffffffff),'32-bit write failed')
 mask=mask or 0xffffffff
 assert(u32(address)&amp;mask==(value&amp;mask),'32-bit verification failed')
end
local function put8(address,value)
 assert(writeBytes(address,value&amp;255),'Byte write failed')
 assert(readBytes(address,1)==value,'Byte verification failed')
end
local function fingerprint(address,expected)
 local actual=readBytes(address,#expected,true)
 assert(actual and #actual==#expected,'Protection code unavailable')
 for i,v in ipairs(expected)do assert(actual[i]==v,'Unsupported protection code fingerprint')end
end
local function psx(pointer,size)
 assert(pointer and pointer&gt;=0x80000000 and pointer&lt;0x80200000,'Invalid PlayStation pointer')
 local offset=pointer&amp;0x1fffff
 assert(offset+(size or 1)&lt;=0x200000,'PlayStation object exceeds RAM')
 return offset
end
function T.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xab3d0)==0 and u32(ram+0xaba38)~=0,'Area loading')
 local control=u32(ram+0xab9f4)
 local work=psx(control,0x100)-0x20
 assert(work&gt;=0 and work+0xa28&lt;0x200000,'Invalid Snake actor bounds')
 assert(u32(ram+work+8)==0x8005ad10 and u32(ram+work+0xc)==0x8005b52c,'Snake actor is not live')
 assert(u32(ram+0xaba20)==0x80000000+work+0x9c,'Snake body owner mismatch')
 local target=psx(u32(ram+work+0x89c),0x48)
 assert(u16(ram+target+2)==1,'Collision target is not on the player side')
 return {h=h,ram=ram,work=work,target=target,status=ram+0xaba50}
end
local function sameOwner(c,s)
 return c.ram==s.ram and c.work==s.work and c.target==s.target
end
local function checkCode(ram)
 R.checkFeature('health');R.checkFeature('ammo')
end
local function applyHealth(c,s)
 assert(sameOwner(c,s),'Snake actor/RAM changed; stop and re-enable protection in gameplay')
 -- Match the game's invulnerability state. Zero frames means no expiration.
 local status=u32(c.status)
 if status&amp;INV==0 then put32(c.status,status|INV,INV)end
 if readBytes(c.ram+c.work+0xa24,1)~=0 then put8(c.ram+c.work+0xa24,0)end
 local class=u16(c.ram+c.target)
 if class&amp;MASK~=0 then put16(c.ram+c.target,class&amp;(~MASK&amp;0xffff),MASK)end
end
local function restoreHealth(s)
 if not s.owner then return true end
 assert(getOpenedProcessID()==T.pid,'Cannot restore while attached to another process')
 local c=T.context()
 if not sameOwner(c,s.owner)then
  -- The original actor has been replaced. Its old fields are no longer ours
  -- to write; the new actor was not patched by this ownership record.
  s.owner=nil;return true
 end
 -- Restore only our collision-mask bits, preserving unrelated current flags.
 put16(c.ram+c.target,(u16(c.ram+c.target)&amp;(~MASK&amp;0xffff))|s.originalMask,MASK)
 put8(c.ram+c.work+0xa24,0)
 put32(c.status,u32(c.status)&amp;(~INV&amp;0xffffffff),INV)
 s.owner=nil
 return true
end
local function applyAmmo(c)
 local h=c.h
 for i=1,10 do
  local current,capacity=h.ammo[i],h.ammoMax[i]
  -- Leave unowned weapons and undefined capacities alone.
  if current&gt;=0 and capacity&gt;0 and capacity&lt;=32767 and current&lt;capacity then
   put16(c.ram+0xb4dba+(i-1)*2,capacity,false)
  end
 end
 -- These three firearms use the shared magazine fields. Never change capacity.
 if h.weapon==0 or h.weapon==1 or h.weapon==9 then
  local capacity=h.magazineMax
  if capacity&gt;0 and capacity&lt;=500 and h.magazine&gt;=0 and h.magazine&lt;capacity then
   local total=h.ammoMax[h.weapon+1]
   if total&gt;0 then put16(c.ram+0xab9ec,math.min(capacity,total),false)end
  end
 end
end
function T.disable(kind)
 local s=assert(T[kind],'Unknown option')
 s.enabled=false
 s.requested=false
 if kind=='ammo'then s.ram=nil;s.work=nil;s.stage=nil;s.lastBinding=nil end
 if kind=='health'and s.owner then
  local ok,err=pcall(restoreHealth,s)
  if not ok then s.status='RESTORE PENDING: '..tostring(err);return false,s.status end
 end
 s.mode=nil;s.status='OFF'
 return true
end
local function ammoReady(c)
 return c.h.health&gt;0 and u32(c.ram+0xAB3D4)==0
  and u32(c.ram+0xAB3CC)&amp;0xD40C0000==0 and u32(c.status)&amp;0x20002084==0
  and u32(c.ram+0xBD360+8)==0x800386A4 and u32(c.ram+0xBD360+12)==0x800387E8
  and u16(c.ram+0xBD360+0x2A)==0
end
-- Integral jeep actor: global vitality refill only; never normal Snake fields.
local function jeepContext()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=R.read();local r=h.ram
 assert((h.stage=='s19b' or h.stage=='s19br') and h.health&gt;0 and u32(r+0xAB3D4)==0,'Enter living jeep gameplay')
 assert(u32(r+0xAB3D0)==0 and u32(r+0xABA38)~=0,'Jeep area loading')
 assert(u32(r+0xAB928)==0 and u32(r+0xAB3CC)==0x20000000 and u32(r+0xABA50)==0,'Finish jeep scene or pause')
 assert(u32(r+0xBD368)==0x800386A4 and u32(r+0xBD36C)==0x800387E8 and u16(r+0xBD38A)==0,'Close the menu')
 local work=psx(u32(r+0xAB9F4),0x100)-0x20
 assert(work&gt;=0x10000 and work+0x100&lt;0x200000,'Jeep actor bounds differ')
 assert(u32(r+work+8)==0x80016230 and u32(r+work+12)==0x800DDE20,'Jeep actor identity differs')
 assert(readString(r+0xDDE20,10)=='jeep_sne.c','Jeep actor label differs')
 assert(u32(r+0xABA20)==0x80000000+work+0x9C,'Jeep body ownership differs')
 fingerprint(r+0x16230,{0xE8,0xFF,0xBD,0x27,0x21,0x28,0x80,0x00,0x10,0x00,0xBF,0xAF,0xF4,0x57,0x00,0x0C,0x02,0x00,0x04,0x24,0x10,0x00,0xBF,0x8F,0x00,0x00,0x00,0x00,0x08,0x00,0xE0,0x03})
 R.checkFeature('health')
 return {h=h,ram=r,work=work}
end
local function applyJeepHealth()
 local c=jeepContext();local fresh=jeepContext()
 assert(c.ram==fresh.ram and c.work==fresh.work and c.h.maximum==fresh.h.maximum,'Jeep owner changed')
 -- The jeep uses global vitality. It has no normal Snake target/mask layout.
 if fresh.h.health&lt;fresh.h.maximum then put16(fresh.ram+0xB4DAE,fresh.h.maximum)end
 local s=T.health
 if s.mode~='jeep' then s.rebinds=s.rebinds+1 end
 s.owner=nil;s.resumeOwned=nil;s.mode='jeep';s.requested=true;s.enabled=true
 s.status='ON - jeep health refill | normal invulnerability resumes after jeep'
 return true
end

-- rope.c owns a separate TARGET at work+804. Its Act copies target+26 to
-- GM_Vitality; refilling GM_Vitality alone cannot prevent its death branch.
local ropeProofs={{offset=0xC8364,bytes={176,255,189,39,68,0,177,175,33,136,128,0,72,0,178,175,156,0,50,38,33,32,64,2,11,128,2,60,11,128,5,60,8,0,3,60,76,0,191,175,64,0,176,175,16,186,74,36,35,0,39,138,32,0,39,154,39,0,40,138,36,0,40,154,3,0,71,169,0,0,71,185,7,0,72,169,4,0,72,185,204,179,162,140,32,0,48,38,37,16,67,0,159,210,0,12}},{offset=0xC8648,bytes={4,8,34,142,11,128,3,60,38,0,66,148,152,77,99,36,22,0,98,164,0,20,2,0,2,0,65,4,0,0,0,0,22,0,96,164}},{offset=0xC48EC,bytes={224,255,189,39,16,0,176,175,33,128,128,0,28,0,191,175,24,0,178,175,20,0,177,175,112,15,3,142,0,0,0,0,0,33,98,48,147,0,64,20,0,128,98,48,4,8,17,142,0,0,0,0,6,0,50,150,54,0,64,16,4,0,66,50}},{offset=0xC4A7C,bytes={6,0,34,150,40,0,32,166,42,0,32,166,251,255,66,48,6,0,34,166,11,128,2,60,156,179,70,36,3,0,199,136,0,0,199,152,7,0,200,136,4,0,200,152,47,0,39,170,44,0,39,186,51,0,40,170,48,0,40,186,38,0,34,134,0,0,0,0,11,0,64,28,12,128,2,60,11,128,4,60,204,179,131,140,140,127,66,36,172,14,2,174,176,14,0,174,190,14,0,166,188,14,0,166,0,32,99,52,216,18,3,8,204,179,131,172}},{offset=0xC486C,bytes={32,0,2,36,124,15,130,172,112,15,130,140,4,8,131,140,0,128,66,52,112,15,130,172,0,0,98,148,0,0,0,0,235,255,66,48,8,0,224,3,0,0,98,164,112,15,130,140,4,8,131,140,124,15,133,172,0,128,66,52,112,15,130,172,0,0,98,148,0,0,0,0,235,255,66,48,8,0,224,3,0,0,98,164}}}
local ROPE_MASK=0x14 -- Native TARGET_POWER | TARGET_SEEK.
local function ropeContext()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=R.read();local r=h.ram
 assert(h.stage=='s11d'and h.health&gt;0 and u32(r+0xAB3D4)==0,'Enter living rappel gameplay')
 assert(u32(r+0xAB3D0)==0 and u32(r+0xABA38)~=0 and u32(r+0xAB928)==0,'Rappel loading or paused')
 assert(u32(r+0xAB3CC)==0x20488000 and u32(r+0xABA50)==0,'Finish the rappel scene')
 assert(u32(r+0xBD368)==0x800386A4 and u32(r+0xBD36C)==0x800387E8 and u16(r+0xBD38A)==0,'Close the menu')
 local work=psx(u32(r+0xAB9F4),0x10)-0x20
 assert(work&gt;=0x10000 and work+0x1098&lt;=0x200000,'Rappel actor bounds differ')
 assert(u32(r+work+8)==0x800C8364 and u32(r+work+12)==0x800C868C and u32(r+work+20)==0x800D1DC4,'Rappel actor identity differs')
 assert(readString(r+0xD1DC4,6)=='rope.c'and u32(r+0xABA20)==0x80000000+work+0x9C,'Rappel body/label differs')
 for _,p in ipairs(ropeProofs)do fingerprint(r+p.offset,p.bytes)end
 R.checkFeature('health')
 local target=psx(u32(r+work+0x804),0x48)
 local hp=u16(r+target+0x26)
 assert(u16(r+target+2)==1 and hp&gt;0 and hp&lt;=h.maximum,'Rappel target side/health invalid or depleted')
 local state=u32(r+work+0xEAC)
 assert(state&gt;=0x800C3D50 and state&lt;0x800C8364 and state~=0x800C7EC4 and state~=0x800C7F8C and state~=0x800C8200,'Rappel death/unsupported state')
 return {h=h,ram=r,work=work,target=target}
end
local function ropeSame(c,s)return c.ram==s.ram and c.work==s.work and c.target==s.target end
local function applyRopeHealth()
 local c=ropeContext();local fresh=ropeContext()
 assert(ropeSame(c,fresh)and c.h.maximum==fresh.h.maximum,'Rappel owner changed')
 local s=T.health;local owner=s.ropeOwner
 if not owner or not ropeSame(fresh,owner)then
  owner={ram=fresh.ram,work=fresh.work,target=fresh.target,mask=u16(fresh.ram+fresh.target)&amp;ROPE_MASK}
  s.ropeOwner=owner;s.rebinds=s.rebinds+1
 end
 local a=fresh.ram+fresh.target
 if u16(a)&amp;ROPE_MASK~=0 then put16(a,u16(a)&amp;(~ROPE_MASK&amp;0xFFFF),ROPE_MASK)end
 -- Cancel already-delivered damage, then heal the authoritative private HP.
 if u16(a+6)&amp;4~=0 then put16(a+6,u16(a+6)&amp;0xFFFB,4)end
 for _,o in ipairs({0x28,0x2A})do if u16(a+o)~=0 then put16(a+o,0)end end
 if u16(a+0x26)~=fresh.h.maximum then put16(a+0x26,fresh.h.maximum)end
 if fresh.h.health~=fresh.h.maximum then put16(fresh.ram+0xB4DAE,fresh.h.maximum)end
 s.owner=nil;s.resumeOwned=nil;s.mode='rappel';s.requested=true;s.enabled=true
 s.status='ON - rappel target immunity + private health protection'
 return true
end
local function restoreRopeHealth()
 local s=T.health;local owner=s.ropeOwner;if not owner then return true end
 assert(getOpenedProcessID()==T.pid,'Original process required for rappel restoration')
 local h=R.read();local p=u32(h.ram+0xAB9F4)
 if h.ram~=owner.ram or h.stage~='s11d'or p~=0x80000000+owner.work+0x20 or u32(h.ram+owner.work+8)~=0x800C8364 then
  s.ropeOwner=nil;return true -- Replaced actors do not own these fields.
 end
 local c=ropeContext();assert(ropeSame(c,owner),'Rappel target changed before restoration')
 local a=c.ram+c.target
 put16(a,(u16(a)&amp;(~ROPE_MASK&amp;0xFFFF))|owner.mask,ROPE_MASK)
 s.ropeOwner=nil;return true
end
local disableNormal=T.disable
function T.disable(kind)
 if kind=='health'then
  T.health.requested=false;T.health.enabled=false
  local ok,err=pcall(restoreRopeHealth)
  if not ok then T.health.status='RESTORE PENDING: '..tostring(err);return false,T.health.status end
 end
 return disableNormal(kind)
end
local function applySpecialHealth()
 local h=R.read()
 if h.stage=='s11d'then return applyRopeHealth()end
 local ok=applyJeepHealth();T.health.ropeOwner=nil;return ok
end

function T.enable(kind)
 assert(not T.stopped,'Reload the stopped controller')
 local s=assert(T[kind],'Unknown option')
 if s.enabled then return true end
 assert(not s.owner,'Finish pending health restoration before re-enabling')
 local ok,c=pcall(T.context)
 if not ok then
  if kind=='health' then return applySpecialHealth() end
  error(c)
 end
 checkCode(c.ram)
 assert(c.h.health&gt;0 and u32(c.ram+0xab3d4)==0,'Enter normal living gameplay before enabling')
 if kind=='health'then
  local existing=u32(c.status)&amp;INV~=0
  local frames=assert(readBytes(c.ram+c.work+0xa24,1),'Cannot read invulnerability frames')
  assert(not existing or (frames&gt;0 and frames&lt;128)or s.resumeOwned,'An existing permanent invulnerability state is active; leave it unchanged')
  -- A normal hit's temporary immunity can be extended. OFF then performs its
  -- normal expiration mask, rather than preserving that temporary no-hit mask.
  s.originalMask=existing and MASK or (u16(c.ram+c.target)&amp;MASK)
  s.owner={ram=c.ram,work=c.work,target=c.target}
  local ok,err=pcall(function()
   applyHealth(c,s.owner)
   -- Synchronize the three health values once; no health-value freeze loop.
   put16(c.ram+c.target+0x26,c.h.maximum)
   put16(c.ram+c.work+0xa22,c.h.maximum)
   put16(c.ram+0xb4dae,c.h.maximum)
  end)
  if not ok then
   local restored,restoreError=pcall(restoreHealth,s)
   s.status=restored and ('OFF: '..tostring(err))or ('RESTORE PENDING: '..tostring(restoreError))
   error(s.status)
  end
  s.mode='normal';s.status='ON - native invulnerability + initial heal'
  s.requested=true;s.resumeOwned=nil
 elseif kind=='ammo'then
  s.requested=true
  if not ammoReady(c)then s.enabled=false;s.status='WAITING FOR AREA: finish the scene/menu';return true end
  applyAmmo(c);s.ram=c.ram;s.work=c.work;s.stage=c.h.stage
  s.lastBinding={ram=c.ram,work=c.work,stage=c.h.stage}
  s.status='ON - owned ammo/magazines replenish | area rebinds '..s.rebinds
 else error('Unknown option')end
 s.enabled=true
 return true
end
-- Integral-only lifecycle: preserve ammo intent while gameplay is unavailable.
function T.tick()
 if T.stopped then return end
 if not T.health.requested and not T.ammo.requested and not T.health.owner and not T.health.ropeOwner then return end
 if getOpenedProcessID()~=T.pid then
  T.ammo.requested=false;T.ammo.enabled=false
  T.ammo.ram=nil;T.ammo.work=nil;T.ammo.stage=nil;T.ammo.lastBinding=nil
  T.ammo.status='OFF: process changed; re-enable for the new process'
  T.health.enabled=false;T.health.status='WAITING: original process required'
  return
 end
 if not T.health.requested and (T.health.owner or T.health.ropeOwner)then T.disable('health')end
 if not T.health.requested and not T.ammo.requested then return end
 local ok,c=pcall(T.context)
 if not ok then
  T.health.enabled=false;T.ammo.enabled=false
  T.ammo.ram=nil;T.ammo.work=nil;T.ammo.stage=nil
  if T.ammo.requested then T.ammo.status='WAITING FOR AREA: '..tostring(c)end
  if T.health.requested then T.health.status='WAITING FOR AREA: '..tostring(c)
  elseif T.health.owner then T.health.status='RESTORE PENDING: '..tostring(c)end
  if T.health.requested then
   local applied,err=pcall(applySpecialHealth)
   if not applied then T.health.status='WAITING FOR AREA: '..tostring(err)end
  end
  return
 end
 -- Existing health ownership/restoration behavior is unchanged.
 T.health.ropeOwner=nil -- Normal actor identity proves the rope actor was replaced.
 if T.health.requested then
  local rebound=T.health.owner and not sameOwner(c,T.health.owner)
  if rebound then
   T.health.resumeOwned=T.health.owner.ram==c.ram
   T.health.owner=nil;T.health.enabled=false
  end
  local applied,err=pcall(function()
   if not T.health.owner then T.health.enabled=false;T.enable('health')
   else applyHealth(c,T.health.owner)end
  end)
  if not applied then
   T.health.enabled=false;T.health.status='WAITING FOR AREA: '..tostring(err)
  else
   if rebound then T.health.rebinds=T.health.rebinds+1 end
   T.health.enabled=true;T.health.status='ON - native invulnerability | area rebinds '..T.health.rebinds
  end
 end
 if T.ammo.requested then
  local s=T.ammo
  local applied,err=pcall(function()
   assert(ammoReady(c),'Finish loading, menus, scenes or restricted actions')
   R.checkFeature('ammo')
   local fresh=T.context()
   assert(fresh.ram==c.ram and fresh.work==c.work and fresh.h.stage==c.h.stage and ammoReady(fresh),'Player/area changed during ammo validation')
   applyAmmo(fresh)
   local previous=s.lastBinding
   if previous and (previous.ram~=fresh.ram or previous.work~=fresh.work or previous.stage~=fresh.h.stage)then s.rebinds=s.rebinds+1 end
   s.ram=fresh.ram;s.work=fresh.work;s.stage=fresh.h.stage
   s.lastBinding={ram=fresh.ram,work=fresh.work,stage=fresh.h.stage}
  end)
  if not applied then
   s.enabled=false;s.ram=nil;s.work=nil;s.stage=nil
   s.status='WAITING FOR AREA: '..tostring(err)
  else
   s.enabled=true;s.status='ON - owned ammo/magazines replenish | area rebinds '..s.rebinds
  end
 end
end
function T.stopAll()
 local restored=T.disable('health');T.disable('ammo')
 if not restored then return false,T.health.status end
 T.stopped=true;T.timer.Enabled=false;T.timer.destroy();T.timer=nil
 if INTToggles==T then INTToggles=nil end
 return true
end
T.timer=createTimer(nil,false);T.timer.Interval=50;T.timer.OnTimer=T.tick;T.timer.Enabled=true
INTToggles=T
return T
]====]):sub(2),
 [ [====[Integral/int-torture-health.lua]====] ]=([====[!-- Generated by analysis/build-integral-boss.py.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=INTReader or dofile(dir..'int-reader.lua')
local T={pid=R.pid,status='OFF',stopped=true,writes=0}
local function u16(a)return assert(readSmallInteger(a))&amp;0xFFFF end
local function u32(a)return assert(readInteger(a))&amp;0xFFFFFFFF end
function T.context()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=R.read();local r=h.ram
 assert(h.stage=='s03b'and h.alertMode==10,'Torture is not active')
 assert(u32(r+0xAB3D0)==0 and u32(r+0xABA38)~=0,'Torture area loading')
 assert(u32(r+0xAB3D4)==0 and h.health&gt;0,'Torture health refill cannot undo game over')
 local p=u32(r+0xAB9F4);assert(p&gt;=0x80010020 and p&lt;0x801FF000,'Torture player unavailable')
 local w=(p&amp;0x1FFFFF)-0x20
 assert(u32(r+w+8)==0x800C6600 and u32(r+w+12)==0x800C6774,'Torture actor differs')
 local n=u32(r+w+20);assert(n&gt;=0x80000000 and n&lt;0x801FFFD0 and readString(r+(n&amp;0x1FFFFF),48)=='torture.c','Torture identity differs')
 assert(u32(r+0xABA20)==0x80000000+w+0x9C,'Torture body ownership differs')
 for _,p in ipairs(T.proofs)do
  local b=assert(readBytes(r+p.offset,#p.bytes,true));for i=1,#p.bytes do assert(b[i]==p.bytes:byte(i),'Torture native health code differs')end
 end
 local hp=u16(r+w+0x804);assert(hp&gt;0 and hp&lt;=h.maximum,'Torture private health invalid or already depleted')
 return {h=h,ram=r,work=w,hp=hp}
end
function T.refill()
 local c=T.context();local r,w=c.ram,c.work;local again=T.context()
 assert(again.ram==r and again.work==w and again.h.maximum==c.h.maximum,'Torture owner changed')
 -- The torture actor copies private halfword804 into GM_Vitality every frame.
 -- Keep both values full; no damage, phase, outcome or input fields are changed.
 for _,a in ipairs({r+w+0x804,r+0xB4DAE})do
  if u16(a)~=c.h.maximum then assert(writeSmallInteger(a,c.h.maximum),'Torture heal failed');T.writes=T.writes+1 end
 end
 T.status='ON - torture health '..c.h.maximum..'/'..c.h.maximum
 return c
end
function T.stop(reason)
 if T.stopped then return end
 T.stopped=true;T.status=reason or 'OFF'
 if T.timer then T.timer.Enabled=false;T.timer.destroy();T.timer=nil end
 local row=getAddressList().getMemoryRecordByID(513);if row and row.Active then row.Active=false end
end
function T.tick()
 if T.stopped or T.busy then return end;T.busy=true
 local ok,err=pcall(function()
  assert(getOpenedProcessID()==T.pid,'Attached process changed')
  local h=R.read();assert(h.stage=='s03a'or h.stage=='s03b'or h.stage=='s03c'or h.stage=='s03d','Left the torture/cell sequence')
  assert(h.health&gt;0 and u32(h.ram+0xAB3D4)==0,'Game over')
  if h.stage~='s03b'or u32(h.ram+0xAB3D0)~=0 or u32(h.ram+0xAB9F4)==0 then
   T.status='Waiting for next torture round; no writes';return
  end
  T.refill()
 end);T.busy=false
 if not ok then T.stop('Stopped: '..tostring(err))end
end
function T.enable()
 assert(not INTTortureHealth or INTTortureHealth.stopped,'Torture protection already active')
 local h=R.read();assert(h.stage=='s03a'or h.stage=='s03b'or h.stage=='s03c'or h.stage=='s03d','Enter the torture/cell sequence')
 T.stopped=false;INTTortureHealth=T;T.tick();assert(not T.stopped,T.status)
 T.timer=createTimer(nil,false);T.timer.Interval=100;T.timer.OnTimer=T.tick;T.timer.Enabled=true
 return T
end
T.proofs={{offset=0xC6600,bytes=('e0ffbd271800b2af219080001400b1af9c005126212020020b80053c74b3a28cfff703241c00bfaf1000b0af2410430074b3a2ac0b80053cccb3a28c0008033c251043009fd2000cccb3a2ac2000502621200002b4004396520045962200429623186500211043009f96000c220042a6bdd2000c2120200221200002f168000c980745260b80023c10ba4a242300478a2000479a2700488a2400489a030047a9000047b9070048a9040048b99c00428e00000000840242940b80033cb87762a49c00428e0000000088024294b8777024020002a69c00428e000000008c02429400000000040002a60b80023c040843860408449602006104984d422421200000160044a4b4004296212040022f19030c520042a600084286000000000100423006004010280004262c084526499a000c03000624d7190308000000002b00478a2800479a2f00488a2c00489a2b0007aa280007ba2f0008aa2c0008ba1c00bf8f1800b28f1400b18f1000b08f0800e0032000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0xC5900,bytes=('180822961c0820a60100422468160308180822a69e082486a6082286b6082386231082001a00430002006014000000000d000700ffff0124040061140080013c02004114000000000d00060012180000ae08228600000000211843002a106400030040100100a22421188000180822a668160308ae0823a61c08229600000000010042241c0822a600140200031402000300431400000000180820a61c0820a64ec2000cac082426b60022860000000009004010000000002708288a2408289a2b08298a2808299a230028aa200028ba270029aa240029ba3800bf8f3400b58f3000b48f2c00b38f2800b28f2400b18f2000b08f0800e0034000bd27c0ffbd273000b0af218080003400b1af2188a0000f0020163800bfaf7a9305341f11030c07000624aa00038602000224050062109c000426212840002130000035d3000c040007242000042616ca000cb500052421200002212800003411030c010006240800222a040040102000042624080526b599000c03000624b60002860000000018004010000000005c08029600000000010042245c0802a65e0803965c0802960000000009004310212000027a9305341f11030c07000624212000025c0806965e3805241f11030c0200c6240c80023cf85a4224080802ae1a0800a6180800a60c0800ae3800bf8f3400b18f3000b08f0800e0034000bd27d0ffbd272000b0af218080002800bfaf2400b1af5e0811961b00a01406000224aa00038600000000050062109c000426212840002130000035d3000c0f0007244008028e000000000f004004060800a6010002241000a2a71800a2271400a2af5c080296000000000300511400000000dd1603081800a0af1800a2af4008048ecb7f000c1000a5275c080296000000002c005110000000001808028600000000160040140000000002080286000000000200423011004014010002241a081186000000000d00221600000000245c000c1000042421200002344f05241f11030c21300000212000025c0806965e3805241f11030c0800c624180811a67b25030c0000000005004010000000001a08029600000000010042241a0802a61a08038602000224250062140c80023c20544224080802ae1a0800a6180800a62d1703080c0800ae18080286000000001900401400000000020802860000000002004230100040140b80043c000802960000000004004234000802a6ccb3828c0200033c251043007429030cccb382ac212000021d4905241f11030c0200062401000224180802a6180802860000000003004010000000009511030c212000022800bf8f2400b18f2000b08f0800e0033000bd27'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0xC5E48,bytes=('213080003408c28c00000000020042940000000020004230060040100b80043c0408c2944a08c39400000000211043000408c2a40408c384b04d8284000000002a104300b04d839402004010000000000408c3a44c08c294000000000500a214000000000208c2941008c0acfdff42300208c2a40800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
return T
]====]):sub(2),
 [ [====[Integral/inventory-panel.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Inventory picker. Opening/refreshing this window only reads game state.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTInventoryPanel and INTInventoryPanel.pid==getOpenedProcessID()then
 INTInventoryPanel.show();return INTInventoryPanel
end
if INTInventoryPanel then INTInventoryPanel.stop()end
local G=dofile(dir..'int-inventory.lua')
local P={pid=G.pid,inventory=G,stopped=false}
local form=createForm(false);P.form=form;form.Caption='Integral - Weapon &amp; Gadget Selector'
form.Width=750;form.Height=675;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local title=createLabel(form);title.Left=16;title.Top=10
title.Caption='Add any weapon or gadget to Snake\'s inventory.'
local function label(parent,x,y,text)
 local l=createLabel(parent);l.Left=x;l.Top=y;l.Caption=text;return l
end
local function button(parent,x,y,text,action)
 local b=createButton(parent);b.Left=x;b.Top=y;b.Width=178;b.Height=30;b.Caption=text;b.OnClick=action;return b
end
local function displayName(kind,id)
 if id&lt;0 then return 'None'end
 local list=kind=='weapon'and G.weapons or G.gadgets
 return list[id+1]and list[id+1].name or '?'
end
local function errorText(err)return tostring(err):match(': ([^\r\n]+)$')or tostring(err)end
local rows={}
local function selected(row)return row.list[row.combo.ItemIndex+1]end
local function act(row,equipping)
 local e=assert(selected(row),'Select equipment')
 local ok,err=pcall(G.grant,row.kind,e.id,row.amount.Text,equipping)
 P.error=not ok and errorText(err)or nil
 if ok then G.status=e.name..(equipping and ' added; equipment switch requested.'or ' added to inventory.')end
 P.tick()
end
local function group(kind,y,caption,list)
 local box=createGroupBox(form);box.Left=12;box.Top=y;box.Width=710;box.Height=170;box.Caption=caption
 local row={kind=kind,list=list,group=box};rows[#rows+1]=row
 local combo=createComboBox(box);row.combo=combo;combo.Left=12;combo.Top=24;combo.Width=325;combo.Style='csDropDownList'
 for _,e in ipairs(list)do combo.Items.add(e.name)end
 row.amountLabel=label(box,355,27,kind=='weapon'and 'Ammo stock' or 'Stock')
 local amount=createEdit(box);row.amount=amount;amount.Left=475;amount.Top=22;amount.Width=95
 row.add=button(box,12,64,'Add to inventory',function()act(row,false)end)
 row.equip=button(box,200,64,'Add + equip',function()act(row,true)end)
 row.unequip=button(box,388,64,'Unequip',function()
  local ok,err=pcall(G.equip,kind,-1);P.error=not ok and errorText(err)or nil;P.tick()
 end)
 local info=label(box,12,105,'');row.info=info;info.AutoSize=false;info.WordWrap=true;info.Width=678;info.Height=53
 combo.OnChange=function()
  local e=selected(row);if e then amount.Text=tostring(e.stock or 1)end
  P.error=nil;if P.tick then P.tick()end
 end
 combo.ItemIndex=0;amount.Text=tostring(list[1].stock or 1)
 return row
end
P.weapon=group('weapon',40,'Weapons - full catalog',G.weapons)
P.gadget=group('gadget',220,'Gadgets and items - full catalog',G.gadgets)
local help=label(form,16,399,'Added equipment stays in inventory when this window closes.')
local memo=createMemo(form);P.memo=memo;memo.Left=12;memo.Top=425;memo.Width=710;memo.Height=195
memo.ReadOnly=true;memo.WordWrap=true;memo.ScrollBars='ssVertical';memo.Font.Name='Consolas';memo.Font.Size=10
function P.tick()
 if P.stopped then return end
 local ok,c=pcall(G.inspect);P.state=ok and c or nil
 for _,row in ipairs(rows)do
  local e=selected(row);local ready=ok and c.ready and e~=nil
  row.add.Enabled=not not ready;row.equip.Enabled=ready and e.equipable~=false or false
  row.unequip.Enabled=not not ready
  row.amount.Enabled=ready and (row.kind=='weapon'or e.kind~=nil)or false
  row.amountLabel.Caption=row.kind=='weapon'and 'Ammo stock'or e and e.kind=='level'and 'Card level'or e and e.kind=='timer'and 'Timer value'or 'Stock'
  if e then
   local raw=ok and (row.kind=='weapon'and c.h.ammo[e.id+1]or c.inventory[e.id])or nil
   local current=raw~=nil and raw~=0xffff and raw&gt;=0 and ((e.id==23 and row.kind=='gadget'and raw==0)and 'Attached to SOCOM'or tostring(raw&amp;0x7fff))or 'Not owned'
   row.info.Caption='In inventory: '..current..'\r\n'..(e.note or (row.kind=='weapon'and 'Grant at least this stock; capacity is raised when needed.'or e.kind=='consumable'and 'Grant at least this stock; capacity is raised when needed.'or 'Adds this item to inventory.'))
  end
 end
 if not ok then memo.Lines.Text='Waiting for normal gameplay.\r\n'..errorText(c);return end
 local text={P.error and ('Action: '..P.error)or G.status,'',
  'Equipped weapon: '..displayName('weapon',c.activeWeapon),
  'Equipped gadget: '..displayName('gadget',c.activeGadget),
  'Area: '..c.stage..' | Inventory actions are one-shot.',
  'Health/no-alert toggles continue independently.','', 'Weapon inventory:'}
 for _,e in ipairs(G.weapons)do
  local n=c.h.ammo[e.id+1]
  text[#text+1]=string.format('  %-15s %s',e.name,n&lt;0 and 'Not owned'or (n..' / '..c.h.ammoMax[e.id+1]))
 end
 if G.logError then text[#text+1]='Action log: '..errorText(G.logError)end
 memo.Lines.Text=table.concat(text,'\r\n')
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 G.closeLog()
 if not closing then form.OnClose=nil;form.destroy()end
 if INTInventoryPanel==P then INTInventoryPanel=nil end
 local record=getAddressList().getMemoryRecordByID(505)
 if record and record.Description:match('^Weapon &amp; gadget selector')and record.Active then record.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=250;timer.OnTimer=P.tick
INTInventoryPanel=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[Integral/room-loader-panel.lua]====] ]=([====[!-- Generated by analysis/build-integral-rooms.py.
-- Native CE dashboard. Reading/filtering/selecting a destination never writes.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTRoomPanel and INTRoomPanel.pid==getOpenedProcessID()then INTRoomPanel.show();return INTRoomPanel end
if INTRoomPanel then INTRoomPanel.stop()end
local W=dofile(dir..'int-room-loader.lua');local P={pid=W.pid,loader=W,stopped=false,visible={}}
local form=createForm(false);P.form=form;form.Caption='Integral - Room &amp; Encounter Loader'
form.Width=850;form.Height=700;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local function label(x,y,text,width,height)
 local l=createLabel(form);l.Left=x;l.Top=y;l.Caption=text
 if width then l.AutoSize=false;l.Width=width;l.Height=height or 24;l.WordWrap=true end
 return l
end
label(16,12,'ROOM &amp; ENCOUNTER LOADER')
local current=label(16,44,'Reading Integral...',800,36);P.current=current
label(16,91,'Show');local group=createComboBox(form);P.group=group
group.Left=66;group.Top=86;group.Width=208;group.Style='csDropDownList'
for _,name in ipairs({'All rooms &amp; encounters','Story rooms','Encounters','Scenes / variants'})do group.Items.add(name)end;group.ItemIndex=0
label(292,91,'Search');local search=createEdit(form);P.search=search;search.Left=355;search.Top=86;search.Width=460
local list=createListBox(form);P.list=list;list.Left=16;list.Top=128;list.Width=800;list.Height=258
local details=label(16,399,'Select a destination.',800,74);P.details=details
local load=createButton(form);P.loadButton=load;load.Left=16;load.Top=480;load.Width=238;load.Height=34;load.Caption='Load selected room'
local back=createButton(form);P.backButton=back;back.Left=270;back.Top=480;back.Width=238;back.Height=34;back.Caption='Load previous room'
local refresh=createButton(form);refresh.Left=524;refresh.Top=480;refresh.Width=142;refresh.Height=34;refresh.Caption='Refresh'
local status=createMemo(form);P.memo=status;status.Left=16;status.Top=528;status.Width=800;status.Height=106;status.ReadOnly=true;status.WordWrap=true;status.ScrollBars='ssVertical'
label(16,643,'Integral story game only. Arenas do not reset defeated bosses. Other discs / scenes may need game-driven transitions.',800,36)
local function errorText(e)return tostring(e):match(': ([^\r\n]+)$')or tostring(e)end
function P.selected()return P.visible[list.ItemIndex+1]end
local function describe()
 local e=P.selected()
 details.Caption=e and (e.name..'  ['..e.id..']'..(e.encounter and '\r\nEncounter: '..e.encounter or '')..'\r\n'..(e.spawn_verified and 'Interior placement checked. 'or e.tested_load and 'Load tested in live Integral. 'or 'Destination load untested. ')..e.note)or 'Select a destination.'
end
function P.filter()
 local old=P.selected();local wanted=group.Items[group.ItemIndex];local query=search.Text:lower()
 list.Items.clear();P.visible={}
 for _,e in ipairs(W.catalog)do
  local haystack=(e.id..' '..e.name..' '..(e.encounter or '')):lower()
  if (group.ItemIndex==0 or e.group==wanted)and haystack:find(query,1,true)then
   P.visible[#P.visible+1]=e
   list.Items.add(string.format('%s   %s%s',e.id,e.name,e.encounter and ('  |  '..e.encounter)or ''))
  end
 end
 list.ItemIndex=#P.visible&gt;0 and 0 or -1
 if old then for i,e in ipairs(P.visible)do if e.id==old.id then list.ItemIndex=i-1;break end end end
 describe();if P.tick then P.tick()end
end
function P.tick()
 if P.stopped then return end
 if getOpenedProcessID()~=P.pid then P.stop();return end
 local ok,s=pcall(W.poll);P.state=ok and s or nil
 local e=P.selected();load.Enabled=ok and s.ready and e~=nil or false
 back.Enabled=ok and ((s.ready and s.previous~=nil)or s.canRecover)or false
 back.Caption=ok and s.canRecover and 'Return from empty scene'or 'Load previous room'
 if ok then
  current.Caption=string.format('Current room: %s  |  Snake HP: %d / %d  |  %s',s.stage,s.health,s.maximum,s.ready and 'Ready to load'or 'Waiting for gameplay')
 else current.Caption='Waiting for Integral gameplay'end
 local text={P.error and ('Action: '..P.error)or W.status}
 if not ok then text[#text+1]=errorText(s)elseif s.reason then text[#text+1]=errorText(s.reason)end
 if W.previous then text[#text+1]='Previous room: '..W.previous..' (room only; entry position follows game rules)'end
 if W.logError then text[#text+1]='Log: '..errorText(W.logError)end
 status.Lines.Text=table.concat(text,'\r\n')
end
local function act(fn)
 local ok,err=pcall(fn);P.error=not ok and errorText(err)or nil;P.tick()
end
load.OnClick=function()act(function()local e=assert(P.selected(),'Select a destination');W.request(e.id)end)end
back.OnClick=function()act(function()if P.state and P.state.canRecover then W.recoverPrevious()else W.returnPrevious()end end)end
refresh.OnClick=function()P.error=nil;P.tick()end
list.OnSelectionChange=function()describe();P.tick()end
group.OnChange=P.filter;search.OnChange=P.filter
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if INTRoomPanel==P then INTRoomPanel=nil end
 local row=getAddressList().getMemoryRecordByID(512);if row and row.Active then row.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
P.timer=createTimer(form,false);P.timer.Interval=500;P.timer.OnTimer=P.tick
INTRoomPanel=P;P.filter();P.tick();P.timer.Enabled=true;P.show()
return P
]====]):sub(2),
 [ [====[Integral/statistics-panel.lua]====] ]=([====[!-- Generated by analysis/build-integral.py; validated mapping required before live writes.
-- Table-style statistics editor. Its refresh timer performs target reads only.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if INTStatisticsPanel and INTStatisticsPanel.pid==getOpenedProcessID()then INTStatisticsPanel.show();return INTStatisticsPanel end
if INTStatisticsPanel then INTStatisticsPanel.stop()end
local S=dofile(dir..'int-stats.lua')
local P={pid=S.pid,stopped=false,rows={}}
local form=createForm(false);P.form=form;form.Caption='Integral - Game Statistics'
form.Width=775;form.Height=655;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local function label(x,y,text,width)
 local l=createLabel(form);l.Left=x;l.Top=y;l.Caption=text
 if width then l.AutoSize=false;l.Width=width;l.Height=36;l.WordWrap=true end
 return l
end
local function edit(x,y,width)
 local e=createEdit(form);e.Left=x;e.Top=y;e.Width=width;return e
end
local function button(x,y,width,text,fn)
 local b=createButton(form);b.Left=x;b.Top=y;b.Width=width;b.Height=28;b.Caption=text;b.OnClick=fn;return b
end
local function action(fn)
 local ok,err=pcall(fn);P.error=not ok and tostring(err)or nil;P.tick()
end
label(16,10,'Ranking statistics - changes apply only when you click Apply.')
P.info=label(16,36,'',735)
label(16,79,'Statistic');label(282,79,'Current');label(400,79,'New value')
for i,e in ipairs(S.fields)do
 local y=105+(i-1)*34;local row={field=e};P.rows[i]=row
 label(16,y+4,e.name);row.current=label(282,y+4,'--')
 row.input=edit(400,y,115)
 row.apply=button(540,y,100,'Apply',function()action(function()S.setCounter(e.key,row.input.Text)end)end)
end
label(16,390,'Play time (HH : MM : SS)');P.timeCurrent=label(282,390,'--')
P.hours=edit(400,385,57);P.minutes=edit(464,385,48);P.seconds=edit(519,385,48)
P.applyTime=button(590,385,150,'Apply play time',function()action(function()S.setTime(P.hours.Text,P.minutes.Text,P.seconds.Text)end)end)
P.copy=button(400,423,205,'Copy current to inputs',function()
 action(function()
  local c=S.inspect()
  for _,row in ipairs(P.rows)do row.input.Text=tostring(c.values[row.field.key])end
  P.hours.Text=tostring(c.hours);P.minutes.Text=tostring(math.floor(c.seconds/60));P.seconds.Text=tostring(c.seconds%60)
 end)
end)
P.extra=label(16,463,'',730)
label(16,504,'Edits stay in this run and may be stored by a normal save. No counters are frozen.',730)
label(16,541,'Difficulty and special-item use can also affect rank. This editor does not predict a final grade.',730)
P.status=label(16,582,'',735);P.status.Height=54
function P.tick()
 if P.stopped then return end
 local ok,c=pcall(S.inspect);P.state=ok and c or nil
 local writable=ok and pcall(S.context,true)
 local ready=ok and c.ready and writable
 for _,row in ipairs(P.rows)do row.current.Caption=ok and tostring(c.values[row.field.key])or '--';row.apply.Enabled=not not ready end
 P.applyTime.Enabled=not not ready;P.copy.Enabled=not not ready
 P.timeCurrent.Caption=ok and c.playTime or '--'
 P.info.Caption=ok and ('Area: '..c.stage..' | Difficulty: '..c.difficulty..' (read-only)')or 'Waiting for normal gameplay.'
 P.extra.Caption=ok and ('Stage time: '..c.stageTime..' | Last-save time: '..c.lastSaveTime..' (read-only)')or ''
 P.status.Caption=P.error or (not ok and tostring(c))or S.status
 if S.logError then P.status.Caption=P.status.Caption..' Log: '..S.logError end
 -- Initialize once; refresh never overwrites text the user is editing.
 if ok and not P.initialized then
  for _,row in ipairs(P.rows)do row.input.Text=tostring(c.values[row.field.key])end
  P.hours.Text=tostring(c.hours);P.minutes.Text=tostring(math.floor(c.seconds/60));P.seconds.Text=tostring(c.seconds%60);P.initialized=true
 end
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if INTStatisticsPanel==P then INTStatisticsPanel=nil end
 local r=getAddressList().getMemoryRecordByID(506)
 if r and r.Description:match('^Game statistics editor')and r.Active then r.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=500;timer.OnTimer=P.tick
INTStatisticsPanel=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[inventory-panel.lua]====] ]=([====[!-- Inventory picker. Opening/refreshing this window only reads game state.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSInventoryPanel and MGSInventoryPanel.pid==getOpenedProcessID()then
 MGSInventoryPanel.show();return MGSInventoryPanel
end
if MGSInventoryPanel then MGSInventoryPanel.stop()end
local G=dofile(dir..'mgs-inventory.lua')
local P={pid=G.pid,inventory=G,stopped=false}
local form=createForm(false);P.form=form;form.Caption='Metal Gear Solid - Weapon &amp; Gadget Selector'
form.Width=750;form.Height=675;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local title=createLabel(form);title.Left=16;title.Top=10
title.Caption='Add any weapon or gadget to Snake\'s inventory.'
local function label(parent,x,y,text)
 local l=createLabel(parent);l.Left=x;l.Top=y;l.Caption=text;return l
end
local function button(parent,x,y,text,action)
 local b=createButton(parent);b.Left=x;b.Top=y;b.Width=178;b.Height=30;b.Caption=text;b.OnClick=action;return b
end
local function displayName(kind,id)
 if id&lt;0 then return 'None'end
 local list=kind=='weapon'and G.weapons or G.gadgets
 return list[id+1]and list[id+1].name or '?'
end
local function errorText(err)return tostring(err):match(': ([^\r\n]+)$')or tostring(err)end
local rows={}
local function selected(row)return row.list[row.combo.ItemIndex+1]end
local function act(row,equipping)
 local e=assert(selected(row),'Select equipment')
 local ok,err=pcall(G.grant,row.kind,e.id,row.amount.Text,equipping)
 P.error=not ok and errorText(err)or nil
 if ok then G.status=e.name..(equipping and ' added; equipment switch requested.'or ' added to inventory.')end
 P.tick()
end
local function group(kind,y,caption,list)
 local box=createGroupBox(form);box.Left=12;box.Top=y;box.Width=710;box.Height=170;box.Caption=caption
 local row={kind=kind,list=list,group=box};rows[#rows+1]=row
 local combo=createComboBox(box);row.combo=combo;combo.Left=12;combo.Top=24;combo.Width=325;combo.Style='csDropDownList'
 for _,e in ipairs(list)do combo.Items.add(e.name)end
 row.amountLabel=label(box,355,27,kind=='weapon'and 'Ammo stock' or 'Stock')
 local amount=createEdit(box);row.amount=amount;amount.Left=475;amount.Top=22;amount.Width=95
 row.add=button(box,12,64,'Add to inventory',function()act(row,false)end)
 row.equip=button(box,200,64,'Add + equip',function()act(row,true)end)
 row.unequip=button(box,388,64,'Unequip',function()
  local ok,err=pcall(G.equip,kind,-1);P.error=not ok and errorText(err)or nil;P.tick()
 end)
 local info=label(box,12,105,'');row.info=info;info.AutoSize=false;info.WordWrap=true;info.Width=678;info.Height=53
 combo.OnChange=function()
  local e=selected(row);if e then amount.Text=tostring(e.stock or 1)end
  P.error=nil;if P.tick then P.tick()end
 end
 combo.ItemIndex=0;amount.Text=tostring(list[1].stock or 1)
 return row
end
P.weapon=group('weapon',40,'Weapons - full catalog',G.weapons)
P.gadget=group('gadget',220,'Gadgets and items - full catalog',G.gadgets)
local help=label(form,16,399,'Added equipment stays in inventory when this window closes.')
local memo=createMemo(form);P.memo=memo;memo.Left=12;memo.Top=425;memo.Width=710;memo.Height=195
memo.ReadOnly=true;memo.WordWrap=true;memo.ScrollBars='ssVertical';memo.Font.Name='Consolas';memo.Font.Size=10
function P.tick()
 if P.stopped then return end
 if not MGSDashboard or MGSDashboard.stopped then P.stop();return end
 local ok,c=pcall(G.inspect);P.state=ok and c or nil
 for _,row in ipairs(rows)do
  local e=selected(row);local ready=ok and c.ready and e~=nil
  row.add.Enabled=not not ready;row.equip.Enabled=ready and e.equipable~=false or false
  row.unequip.Enabled=not not ready
  row.amount.Enabled=ready and (row.kind=='weapon'or e.kind~=nil)or false
  row.amountLabel.Caption=row.kind=='weapon'and 'Ammo stock'or e and e.kind=='level'and 'Card level'or e and e.kind=='timer'and 'Timer value'or 'Stock'
  if e then
   local raw=ok and (row.kind=='weapon'and c.h.ammo[e.id+1]or c.inventory[e.id])or nil
   local current=raw~=nil and raw~=0xFFFF and raw&gt;=0 and ((e.id==23 and row.kind=='gadget'and raw==0)and 'Attached to SOCOM'or tostring(raw&amp;0x7FFF))or 'Not owned'
   row.info.Caption='In inventory: '..current..'\r\n'..(e.note or (row.kind=='weapon'and 'Grant at least this stock; capacity is raised when needed.'or e.kind=='consumable'and 'Grant at least this stock; capacity is raised when needed.'or 'Adds this item to inventory.'))
  end
 end
 if not ok then memo.Lines.Text='Waiting for normal gameplay.\r\n'..errorText(c);return end
 local text={P.error and ('Action: '..P.error)or G.status,'',
  'Equipped weapon: '..displayName('weapon',c.activeWeapon),
  'Equipped gadget: '..displayName('gadget',c.activeGadget),
  'Area: '..c.stage..' | Inventory actions are one-shot.',
  'Health/no-alert toggles continue independently.','', 'Weapon inventory:'}
 for _,e in ipairs(G.weapons)do
  local n=c.h.ammo[e.id+1]
  text[#text+1]=string.format('  %-15s %s',e.name,n&lt;0 and 'Not owned'or (n..' / '..c.h.ammoMax[e.id+1]))
 end
 if G.logError then text[#text+1]='Action log: '..errorText(G.logError)end
 memo.Lines.Text=table.concat(text,'\r\n')
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 G.closeLog()
 if not closing then form.OnClose=nil;form.destroy()end
 if MGSInventoryPanel==P then MGSInventoryPanel=nil end
 local record=getAddressList().getMemoryRecordByID(5)
 if record and record.Description:match('^Weapon &amp; gadget selector')and record.Active then record.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=250;timer.OnTimer=P.tick
MGSInventoryPanel=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[mgs-aura-render.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- US MGS resident, texture-free LINE_F2 primitive. All mutations require the
-- caller to suspend the process and validate a normal-game reader context.
-- Layout/algorithms: libgv/memory.c, libdg/{prim,chanl,sort}.c.
local A={heap=0xB1A88,channel=0xB4164,queue=0xB36F8,size=0x680,count=32}
local function u32(a)return assert(readInteger(a))&amp;0xffffffff end
local function u16(a)return assert(readSmallInteger(a))&amp;0xffff end
local function w32(a,v)assert(writeInteger(a,v&amp;0xffffffff),'Aura write failed')end
local function w16(a,v)assert(writeSmallInteger(a,v&amp;0xffff),'Aura write failed')end
local function bytes(a,n)return assert(readBytes(a,n,true))end
function A.heapState(r)
 local h=r+A.heap;local stat,start,finish,n=u32(h),u32(h+4),u32(h+8),u32(h+12)
 assert(stat==0 or stat==2,'Normal heap busy or layout differs')
 assert(start&gt;=0x800C0000 and finish&gt;start and finish&lt;=0x80200000 and n&gt;=1 and n&lt;511,'Heap bounds differ')
 local units={};local previous=start-1
 for i=0,n do
  local address,tag=u32(h+16+i*8),u32(h+20+i*8)
  assert(address&gt;previous and address&gt;=start and address&lt;=finish and address%16==0 and tag&lt;=2,'Heap units differ')
  units[#units+1]={address=address,tag=tag};previous=address
 end
 assert(units[1].address==start and units[#units].address==finish and units[#units].tag==2,'Heap sentinels differ')
 return {r=r,h=h,n=n,stat=stat,units=units}
end
function A.queueState(r)
 local c=r+A.channel
 assert(u16(c+8)==8 and u16(c+0x52)==256 and u32(c+0x58)==0x80000000+A.queue,'Render channel differs')
 local n,objs=u16(c+0x54),u16(c+0x56)
 assert(objs&gt;=0 and objs&lt;n and n&lt;=256,'Render queue full or invalid')
 local q={};for i=n,255 do
  local p=u32(r+A.queue+i*4)
  assert(p&gt;=0x80010000 and p+0x54&lt;=0x80200000,'Render queue pointer differs')
  q[#q+1]={index=i,pointer=p}
 end
 return {n=n,objs=objs,entries=q}
end
local function unitFor(s,b)
 for i=1,#s.units-1 do local u=s.units[i]
  if u.address==b.guest and s.units[i+1].address==b.guest+A.size and u.tag==2 then return i-1 end
 end
end
function A.owned(r,b)
 if not b or b.ram~=r then return false end
 local s=A.heapState(r)
 if not unitFor(s,b)then return false end
 local a=r+(b.guest&amp;0x1fffff)
 return u32(a+0x670)==0x41555241 and u32(a+0x674)==b.token
  and u32(a+0x20)==0 and (u32(a+0x24)==0 or u32(a+0x24)==0x100)
  and u16(a+0x2a)==32 and u32(a+0x30)==0x00020010
  and u32(a+0x38)==b.guest+0x460 and u32(a+0x40)==b.guest+0x60 and u32(a+0x44)==b.guest+0x260
end
function A.present(r,b)
 local q=A.queueState(r);local found
 for _,e in ipairs(q.entries)do if e.pointer==b.guest then assert(not found,'Duplicate aura primitive');found=e.index end end
 return found,q
end
function A.allocate(c,token)
 local r=c.ram;local s=A.heapState(r);local q=A.queueState(r);local pick
 -- Same first-fit/split rule as GV_AllocMemory2, normal heap USED_UNIT.
 for i=1,#s.units-1 do local u=s.units[i]
  if u.tag==0 and s.units[i+1].address-u.address&gt;A.size then pick=i;break end
 end
 assert(pick,'No free native heap block for aura')
 local guest=s.units[pick].address;local a=r+(guest&amp;0x1fffff)
 local b={ram=r,guest=guest,token=token,stage=c.stage,work=c.work}
 local data={};for i=1,A.size do data[i]=0 end
 local function p16(o,v)data[o+1]=v&amp;255;data[o+2]=(v&gt;&gt;8)&amp;255 end
 local function p32(o,v)p16(o,v);p16(o+2,v&gt;&gt;16)end
 for _,o in ipairs({0,8,16})do p16(o,4096)end
 p32(0x24,0x100) -- invisible until its first valid update
 p16(0x2a,A.count);p16(0x30,16);p16(0x32,2);p16(0x34,8);p16(0x36,4)
 p32(0x38,guest+0x460);p32(0x40,guest+0x60);p32(0x44,guest+0x260)
 p32(0x670,0x41555241);p32(0x674,token)
 for buffer=0,1 do for i=0,A.count-1 do
  local o=0x60+buffer*0x200+i*16;p32(o,0x03000000);p32(o+4,0x40FFFFFF)
 end end
 assert(writeBytes(a,data),'Aura initialization failed')
 -- Prepare the entire descriptor-table edit before committing its count.
 local edited={};for i,u in ipairs(s.units)do
  edited[#edited+1]={address=u.address,tag=i==pick and 2 or u.tag}
  if i==pick then edited[#edited+1]={address=guest+A.size,tag=0}end
 end
 local meta={};for _,u in ipairs(edited)do for _,v in ipairs({u.address,u.tag})do for j=0,3 do meta[#meta+1]=(v&gt;&gt;(8*j))&amp;255 end end end
 assert(writeBytes(s.h+16,meta),'Aura heap registration failed');w32(s.h+12,s.n+1)
 assert(A.owned(r,b),'Aura allocation not registered')
 w32(r+A.queue+(q.n-1)*4,guest);w16(r+A.channel+0x54,q.n-1)
 return b
end
function A.update(c,b,phase,rgb)
 local r=c.ram;assert(A.owned(r,b),'Aura allocation lost');assert(A.present(r,b),'Aura queue entry lost')
 local a=r+(b.guest&amp;0x1fffff);local xyz={}
 for axis=0,2 do local v=u16(r+c.work+0x20+axis*2);xyz[axis+1]=v&gt;=32768 and v-65536 or v end
 for axis=1,3 do w32(a+0x14+(axis-1)*4,xyz[axis])end
 -- Four crossing lines per star; positions are local to Snake's location.
 local offsets={{-80,0,80,0},{0,-100,0,100},{-45,-55,45,55},{-45,55,45,-55}}
 for star=0,7 do
  local angle=phase+star*math.pi/4
  local x,z=math.cos(angle)*700,math.sin(angle)*700
  local y=800+math.sin(phase*1.5+star)*270
  local glow=0.6+0.4*math.sin(phase*4+star*2)^2
  local color=0x40000000
  for axis=1,3 do color=color|(math.floor(rgb[axis]*glow)&lt;&lt;(8*(axis-1)))end
  for line=0,3 do
   local d=offsets[line+1];local i=star*4+line
   local p=a+0x460+i*16
   for endpoint=0,1 do
    w16(p+endpoint*8,math.floor(x+d[endpoint*2+1]+0.5))
    w16(p+endpoint*8+2,math.floor(y+d[endpoint*2+2]+0.5))
    w16(p+endpoint*8+4,math.floor(z+0.5))
   end
   for buffer=0,1 do w32(a+0x60+buffer*0x200+i*16+4,color)end
  end
 end
 w32(a+0x24,0);b.stage=c.stage;b.work=c.work
end
function A.hide(r,b)
 if A.owned(r,b)then w32(r+(b.guest&amp;0x1fffff)+0x24,0x100);return true end
end
function A.detach(r,b)
 assert(A.owned(r,b),'Aura allocation lost before detach')
 A.hide(r,b);local index,q=A.present(r,b)
 if index then
  for i=index,q.n+1,-1 do w32(r+A.queue+i*4,u32(r+A.queue+(i-1)*4))end
  w16(r+A.channel+0x54,q.n+1)
 end
 return true
end
function A.release(r,b)
 -- Caller waits &gt;=4 native frames after detach before retirement. Native
 -- delayed-free compaction then reclaims this single block.
 if not A.owned(r,b)then return false end
 assert(not A.present(r,b),'Cannot free a queued aura')
 local s=A.heapState(r);local i=assert(unitFor(s,b))
 w32(s.h+20+i*8,1);w32(s.h,s.stat|2);return true
end
return A
]====]):sub(2),
 [ [====[mgs-big-head.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- Reversible US normal-Snake head geometry experiment; no game code/hooks.
-- Structs: FoxdieTeam/mgs_reversing include/fmt_kmd.h and libdg/libdg.h.
local options=(...)or{}
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local G=dofile(dir..'mgs-inventory.lua')
local C={pid=getOpenedProcessID(),status='Original model',version=1}
local function u32(a)return assert(readInteger(a))&amp;0xffffffff end
local function u16(a)return assert(readSmallInteger(a))&amp;0xffff end
local function s16(a)local v=u16(a);return v&gt;=32768 and v-65536 or v end
local function s32(a)local v=u32(a);return v&gt;=0x80000000 and v-0x100000000 or v end
local function ptr(r,v,n)
 assert(v&gt;=0x80010000 and v+n&lt;=0x80200000,'Model pointer outside guest RAM')
 return r+(v&amp;0x1fffff)
end
function C.context()
 assert(getOpenedProcessID()==C.pid,'Game process changed')
 local c=options.context and options.context()or G.context(true);local r=c.ram
 if not options.context then assert(c.stage=='s01a','First model test is limited to the Heliport')end
 assert(u32(r+0xAE0A0)==0 and u32(r+0xBFAD0)==0x8003A948 and u32(r+0xBFAD4)==0x8003AA94 and u16(r+0xBFAF2)==0,'Resume normal gameplay and close menus')
 local o=ptr(r,u32(r+c.work+0x9c),0x48+16*0x5c)
 assert(u16(o+0x2e)==16,'Snake render-part count differs')
 local definition=ptr(r,u32(o+0x24),0x20+16*0x58)
 assert(u32(definition)==16,'Snake definition differs')
 local model=ptr(r,u32(o+0x48+6*0x5c+0x40),0x58)
 assert(model==definition+0x20+6*0x58,'Head model is not part6')
 assert(u32(model)==1 and u32(model+4)==81 and s32(model+0x2c)==5 and s32(model+0x30)==-1,'Head geometry layout differs')
 local count=u32(model+0x34);assert(count==67,'Head vertex count differs')
 local vertices=ptr(r,u32(model+0x38),count*8)
 assert(vertices&gt;=definition+0x20+16*0x58,'Head vertices overlap metadata')
 c.object=o;c.definition=definition;c.model=model;c.vertices=vertices;c.count=count
 return c
end
local function same(a,b)
 return a.ram==b.ram and a.work==b.work and a.stage==b.stage and a.object==b.object and a.definition==b.definition and a.model==b.model and a.vertices==b.vertices and a.count==b.count
end
local function round(v)return v&gt;=0 and math.floor(v+0.5)or math.ceil(v-0.5)end
function C.apply(scale)
 assert(not C.binding,'Restore the previous head size first')
 assert(type(scale)=='number'and scale&gt;=0.5 and scale&lt;=2,'Head scale must be0.5..2')
 local c=C.context();local plan={}
 for i=0,c.count-1 do for axis=0,2 do
  local a=c.vertices+i*8+axis*2;local before=s16(a)
  assert(math.abs(before)&lt;=512,'Head vertex range differs')
  local value=round(before*scale);assert(math.abs(value)&lt;=1024)
  plan[#plan+1]={address=a,size=2,before=before,value=value}
 end end
 -- Update only this part's render bounds, retaining joint translation/metadata.
 for i=0,5 do
  local a=c.model+8+i*4;local before=s32(a);assert(math.abs(before)&lt;=512)
  local value=i&lt;3 and math.floor(before*scale)or math.ceil(before*scale)
  plan[#plan+1]={address=a,size=4,before=before,value=value}
 end
 assert(same(c,C.context()),'Model owner changed before apply')
 for _,p in ipairs(plan)do assert((p.size==2 and s16(p.address)or s32(p.address))==p.before,'Model changed before apply')end
 C.binding={context=c,plan=plan,scale=scale}
 for _,p in ipairs(plan)do
  local ok=p.size==2 and writeSmallInteger(p.address,p.value&amp;0xffff)or p.size==4 and writeInteger(p.address,p.value&amp;0xffffffff)
  assert(ok,'Head write interrupted; retain binding for restore')
 end
 C.status='Head scale '..scale..'x; original geometry retained for restore'
 return #plan
end
function C.restore()
 local b=C.binding;if not b then return true end
 assert(same(b.context,C.context()),'Model owner changed; no stale restore')
 for _,p in ipairs(b.plan)do
  local v=p.size==2 and s16(p.address)or s32(p.address)
  assert(v==p.value or v==p.before,'Model changed; restore refused')
 end
 for _,p in ipairs(b.plan)do
  local ok=p.size==2 and writeSmallInteger(p.address,p.before&amp;0xffff)or p.size==4 and writeInteger(p.address,p.before&amp;0xffffffff)
  assert(ok,'Head restore interrupted')
 end
 C.binding=nil;C.status='Original head restored';return true
end
if not options.detached then MGSCosmeticTest=C end
return C
]====]):sub(2),
 [ [====[mgs-boss-actions.lua]====] ]=([====[!-- Optional one-shot boss cheats. The boss observer itself remains read-only.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local A={version=2}
local function u16(a)return assert(readSmallInteger(a),'Target read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Target read unavailable')&amp;0xFFFFFFFF end
local function check(r,offset,hex)
 local expected={};for s in hex:gmatch('%x%x')do expected[#expected+1]=tonumber(s,16)end
 local actual=assert(readBytes(r+offset,#expected,true),'Damage handler unavailable')
 for i,v in ipairs(expected)do assert(actual[i]==v,'Ocelot damage/defeat code differs.')end
end
function A.defeatOcelot()
 local S=dofile(dir..'mgs-stats.lua');local safe=S.context(true)
 local B=dofile(dir..'mgs-boss.lua');local c=B.inspect()
 assert(c.ram==safe.ram,'Game state changed; try again.')
 local list={}
 for _,b in ipairs(c.bosses)do if b.actor.name=='revolver.c'then list[#list+1]=b end end
 assert(#list==1,'A live Ocelot fight must be loaded.')
 local b=list[1];assert(b.hp and b.maxHP and b.target and b.binding,'Ocelot HP layout is not verified.')
 assert(b.hp&gt;0 and b.phaseID~=4,'Ocelot is already defeated.')
 assert(b.phaseID and b.phaseID~=6,'Wait for the opening scene to finish.')
 local r,w,fn=c.ram,b.actor.offset,b.actor.act&amp;0x1FFFFF
 check(r,fn-0x2014,'3C08118E00000000060023960000000004006230')
 check(r,fn-0x1FE8,'3E002386')
 check(r,fn-0x1E70,'2120000204000224FC0802AE')
 check(r,fn-0x1E60,'000900AE')
 check(r,fn-0x1E54,'540800AE')
 assert(u32(r+w+8)==b.actor.act and u32(r+w+12)==b.actor.die,'Boss actor changed.')
 assert(u32(r+w+0x83C)==b.target,'Boss target changed.')
 local target=b.target&amp;0x1FFFFF
 assert(target&gt;=0x10000 and target+0x48&lt;=0x200000,'Target bounds differ.')
 local damaged=u16(r+target+6);local mode=u16(r+target+0x3E)
 assert(damaged&amp;4==0,'Ocelot is processing another hit; try again in a moment.')
 local before=u16(r+target+0x26)
 assert(before==b.hp and before&gt;0 and u32(r+0xADB44)==0,'Fight changed during validation.')
 -- Ordinary mode 0 takes the normal death branch. In particular, it avoids
 -- reusing a previous C4 hit's special HP recalculation.
 assert(writeSmallInteger(r+target+0x3E,0),'Damage mode write failed.')
 assert(writeSmallInteger(r+target+0x26,0),'HP write failed.')
 -- Publish the damage notification last. Normal game code clears this bit,
 -- sets state 4/time 0, updates the health bar and executes the defeat script.
 local current=u16(r+target+6)
 assert(writeSmallInteger(r+target+6,current|4),'Damage notification failed.')
 A.last={pid=B.pid,stage=c.stage,work=w,target=b.target,beforeHP=before,requestedHP=0,previousMode=mode,previousFlags=damaged}
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../logs/ocelot-defeat-actions.csv','a+'))
  local success,why=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,pid,area,actor,target,before_hp,requested_hp,previous_mode,previous_flags\n'))end
   assert(f:write(string.format('%s,%d,%s,%08X,%08X,%d,0,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),B.pid,c.stage,0x80000000+w,b.target,before,mode,damaged)))
  end)
  f:close();assert(success,why)
 end)
 if not ok then A.logError=tostring(err)end
 MGSBossActions=A
 return A.last
end
-- This context deliberately does not require the normal Snake actor: the
-- rooftop Liquid fight uses a different player actor. The reader still checks
-- the installed executable, emulated RAM, region and resident fingerprints.
local function ready(B,c)
 assert(getOpenedProcessID()==B.pid,'Attached process changed.')
 local h=B.reader.read();local r=c.ram
 assert(h.ram==r and h.health&gt;0,'Player or RAM changed.')
 assert(u32(r+0xADB40)==0 and u32(r+0xAE1B0)~=0 and u32(r+0xADB44)==0,'Wait for normal gameplay.')
 assert(u32(r+0xADB3C)&amp;0xD40C0000==0 and u32(r+0xAE1C8)&amp;0x20002084==0,'Finish the scene or restricted action first.')
 assert(readString(r+0xB7500,16)==c.stage,'Area changed.')
 -- No codec, inventory or save-slot menu. Do not invoke any menu operation.
 assert(u32(r+0xBFAC8+8)==0x8003A948 and u32(r+0xBFAC8+12)==0x8003AA94,'Resident menu actor differs.')
 assert(u16(r+0xBFAC8+0x2A)==0,'Close the menu before using boss defeat.')
end
local function sameActor(r,a)
 assert(a.offset&gt;=0x10000 and a.offset+0x4020&lt;=0x200000,'Boss allocation window unavailable.')
 assert(u32(r+a.offset+8)==a.act and u32(r+a.offset+12)==a.die,'Boss actor changed.')
 local name=u32(r+a.offset+20)
 assert(name&gt;=0x80000000 and name&lt;0x80200000 and readString(r+(name&amp;0x1FFFFF),48)==a.name,'Boss identity changed.')
end
function A.defeatCurrentBoss()
 local B=dofile(dir..'mgs-boss.lua');local c=B.inspect()
 assert(#c.bosses==1,'Exactly one supported live boss must be loaded.')
 local b=c.bosses[1]
 -- Preserve the independently verified Ocelot implementation and its log.
 if b.actor.name=='revolver.c'then return A.defeatOcelot()end
 ready(B,c);sameActor(c.ram,b.actor)
 local P=dofile(dir..'mgs-boss-experimental.lua');local plan=P.plan(B,c,b)
 -- Validate the complete plan before the first write. These checks catch
 -- changed targets, phases, code, ownership, pending hits and area loads.
 ready(B,c);sameActor(c.ram,b.actor)
 for _,o in ipairs(plan.owners)do
  assert(u32(c.ram+o.work+8)==o.act and u32(c.ram+o.work+12)==o.die,'Target owner changed.')
  assert(u32(o.pointerAddress)==o.pointer,'Boss target changed.')
  if o.parent then assert(u32(o.parent.address)==o.parent.value,'Tank gunner parent changed.')end
 end
 for _,p in ipairs(plan.proofs)do assert(u32(c.ram+(p.pc&amp;0x1FFFFF))==p.word,'Boss code changed.')end
 local seen={}
 for _,block in ipairs(plan.blocks)do
  if not seen[block.address]then
   seen[block.address]=true
   local bytes=assert(readBytes(block.address,#block.bytes,true),'Boss code unavailable')
   assert(#bytes==#block.bytes,'Incomplete boss code read')
   for i=1,#bytes do assert(bytes[i]==block.bytes:byte(i),'Boss code changed.')end
  end
 end
 local function value(v)return v.size==2 and u16(v.address)or u32(v.address)end
 for _,v in ipairs(plan.conditions)do assert(value(v)==v.value,'Boss vulnerability changed; retry.')end
 for _,list in ipairs({plan.writes,plan.notifications})do
  for _,v in ipairs(list)do assert(value(v)==v.before,'Boss state changed; wait briefly and retry.')end
 end
 local written=0
 local function apply(v)
  local ok;if v.size==2 then ok=writeSmallInteger(v.address,v.value)else ok=writeInteger(v.address,v.value)end
  assert(ok,'Boss write failed after '..written..' writes: '..v.label)
  written=written+1
 end
 for _,v in ipairs(plan.writes)do apply(v)end
 -- Publish damage notifications only after health/counters and impact types.
 for _,v in ipairs(plan.notifications)do apply(v)end
 A.last={pid=B.pid,stage=c.stage,boss=plan.boss,profile=plan.profile,tested=false,work=b.actor.offset,writes=written,targets=#plan.notifications}
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../logs/boss-defeat-actions.csv','a+'))
  local success,why=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,pid,area,boss,experimental,actor,field,address,before,requested\n'))end
   for _,list in ipairs({plan.writes,plan.notifications})do for _,v in ipairs(list)do
    assert(f:write(string.format('%s,%d,%s,%s,true,%08X,%s,%X,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),B.pid,c.stage,plan.profile,0x80000000+b.actor.offset,v.label,v.address,v.before,v.value)))
   end end
  end)
  f:close();assert(success,why)
 end)
 if not ok then A.logError=tostring(err)end
 MGSBossActions=A
 return A.last
end
return A
]====]):sub(2),
 [ [====[mgs-boss-experimental.lua]====] ]=([====[!-- Full encounter roster and source-based experimental defeat planning.
-- This module only reads/plans. mgs-boss-actions.lua performs optional writes.
local P={version=1}
P.catalog={
 ['revolver.c']={id='ocelot',name='Revolver Ocelot',stages={s04b=true,s04c=true},tested=true},
 ['m1e1.c']={id='tank',name='M1 tank / Raven',stages={s05a=true}},
 ['ninja.c']={id='ninja',name='Cyborg Ninja',stages={s08b=true}},
 ['psyco.c']={id='mantis',name='Psycho Mantis',stages={s07b=true}},
 ['wolf2.c']={id='wolf',name='Sniper Wolf',stages={s10a=true,s12a=true}},
 ['hind.c']={id='hind',name='Hind D',stages={s11g=true}},
 ['valcan.c']={id='raven',name='Vulcan Raven',stages={s15c=true}},
 ['mgrex.c']={id='rex',name='Metal Gear REX (current phase)',stages={s17a=true}},
 ['liquid.c']={id='liquid',name='Liquid Snake',stages={s18a=true}},
 ['jeep_liq.c']={id='escape',name='Liquid (escape chase)',stages={s19b=true}},
}
local function u16(a)return assert(readSmallInteger(a),'Target read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xFFFFFFFF end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function record(plan,r,address,size,value,label)
 local before=size==2 and u16(address)or u32(address)
 assert(value&gt;=0 and value&lt;(size==2 and 0x10000 or 0x100000000),'Invalid planned value')
 for _,v in ipairs(plan.writes)do assert(v.address~=address,'Duplicate planned field')end
 plan.writes[#plan.writes+1]={address=address,size=size,value=value,before=before,label=label}
end
function P.plan(B,c,b)
 local profile=assert(P.catalog[b.actor.name],'Boss profile missing')
 assert(profile.stages[c.stage],'Boss/area mismatch')
 assert(profile.id~='ocelot','Ocelot uses the tested action')
 local r,w=c.ram,b.actor.offset
 local plan={boss=profile.name,profile=profile.id,tested=false,ram=r,pid=B.pid,stage=c.stage,actor=b.actor,writes={},notifications={},proofs={},owners={},conditions={},blocks={}}
 local evidence=B.ownership(r,b.actor)
 local function retain(owned)for _,v in ipairs(owned.blocks or {})do plan.blocks[#plan.blocks+1]=v end end
 retain(evidence)
 local function condition(address,size,value)
  plan.conditions[#plan.conditions+1]={address=address,size=size,value=value}
  return value
 end
 local function keep(p)plan.proofs[#plan.proofs+1]=p end
 local function field(offset,value,label,options)
  local e=evidence.fields[offset]
  assert(e and e.read and e.write,'Native read/write proof missing for '..label..'; no changes made')
  if options and options.decrement then assert(e.decrement,'Native decrement proof missing for '..label)end
  local old=s32(r+w+offset);assert(old&gt;=((options and options.minimum)or 0)and old&lt;=((options and options.maximum)or 32767),'Implausible or already finished '..label)
  keep(e.read);keep(e.write);if e.decrement then keep(e.decrement)end
  record(plan,r,r+w+offset,4,value,label)
  return old
 end
 local function targets(actor,owned,requiredParent)
  retain(owned)
  local added=0
  for offset,p in pairs(owned.targets)do
   local ptr=u32(r+actor.offset+offset)
   if ptr&gt;=0x800B8C48 and ptr&lt;0x800B9E48 and (ptr-0x800B8C48)%0x48==0 then
    local t=r+(ptr&amp;0x1FFFFF);local class,side=u16(t),u16(t+2)
    if side==2 and class&amp;4~=0 then
     condition(t,2,class);condition(t+2,2,side)
     assert(u16(t+6)&amp;4==0,'Boss is processing a hit; wait briefly and retry')
     plan.owners[#plan.owners+1]={work=actor.offset,act=actor.act,die=actor.die,pointerAddress=r+actor.offset+offset,pointer=ptr,parent=requiredParent}
     keep(p);local duplicate=false
     for _,n in ipairs(plan.notifications)do if n.address==t+6 then duplicate=true end end
     if not duplicate then
      local mode=(profile.id=='ninja'or profile.id=='liquid')and 3 or 0
      record(plan,r,t+0x3E,2,mode,'ordinary boss damage mode')
      if profile.id=='hind'or profile.id=='rex'then record(plan,r,t+0x44,4,4,'Stinger impact type')
      elseif profile.id=='wolf'then record(plan,r,t+0x44,4,9,'PSG1 impact type')end
      record(plan,r,t+0x26,2,0,'boss-owned target HP')
      plan.notifications[#plan.notifications+1]={address=t+6,size=2,value=u16(t+6)|4,before=u16(t+6),label='damage notification'}
      added=added+1
     end
    end
   end
  end
  return added
 end
 if profile.id=='tank'then
  -- The director's targets are armor, not the gunners' health. Restrict to
  -- a gunner actor with an explicit parent pointer to this director.
  field(0xE08,1,'remaining tank gunners',{minimum=1,maximum=16,decrement=true})
  field(0xE0C,0,'current gunner health')
  local children=0
  for _,a in ipairs(c.actors)do
   if a.name and a.name:match('^m1e1')and a.name~='m1e1.c'and u32(r+a.offset+0x1EC)==0x80000000+w then
    local n=targets(a,B.ownership(r,a),{address=r+a.offset+0x1EC,value=0x80000000+w})
    if n&gt;0 then children=children+n end
   end
  end
  assert(children&gt;0,'No code-owned active tank gunner target; no changes made')
  -- Tank gunners treat damaged as a damage magnitude. Native thresholds
  -- come from the director's positive HP/divisor settings.
  local hp,divisor=s32(r+w+0xD74),s32(r+w+0xDEC)
  assert(hp&gt;0 and hp&lt;=32767 and divisor&gt;0 and divisor&lt;=32767,'Tank damage threshold unavailable')
  assert(s32(r+w+0xF5C)==0,'Tank gunner is in hit recovery; retry when vulnerable')
  condition(r+w+0xD74,4,hp);condition(r+w+0xDEC,4,divisor);condition(r+w+0xF5C,4,0)
  for _,n in ipairs(plan.notifications)do n.value=math.max(4,math.floor(hp/divisor));assert(n.value&lt;=32767)end
 elseif profile.id=='wolf'then
  field(0x6FC,1,'Wolf remaining hits',{minimum=1,maximum=64,decrement=true})
  field(0xA40,0,'Wolf health units')
  assert(s32(r+w+0x748)==0 and s32(r+w+0xA54)==0,'Wolf is protected/in hit recovery; retry when vulnerable')
  condition(r+w+0x748,4,0);condition(r+w+0xA54,4,0)
  assert(targets(b.actor,evidence)&gt;0,'No active Wolf damage target')
 elseif profile.id=='hind'then
  field(0x434,1,'Hind remaining missile hits',{minimum=1,maximum=64,decrement=true})
  field(0x654,0,'Hind health')
  assert(s32(r+w+0x50C)==0 and s32(r+w+0x658)==0,'Hind is protected/in hit recovery; retry when vulnerable')
  condition(r+w+0x50C,4,0);condition(r+w+0x658,4,0)
  local y=u16(r+w+0x22);assert(y&gt;0 and y&lt;32768,'Wait for Hind to be airborne')
  condition(r+w+0x22,2,y)
  assert(targets(b.actor,evidence)&gt;0,'No active Hind damage target')
 elseif profile.id=='raven'then
  field(0x900,0,'Raven health')
  assert(targets(b.actor,evidence)&gt;0,'No active Raven damage target')
 else
  -- For undecompiled REX/Liquid code, require runtime TARGET ownership from
  -- GM_FreeTarget calls. Never guess heap addresses from another playthrough.
  -- Only zero a bar's underlying field when native code also writes it.
  if b.binding then field(b.binding.offset,0,'code-derived boss health units')
  elseif profile.id=='ninja'then field(0x19E4,0,'Ninja health units')end
  assert(targets(b.actor,evidence)&gt;0,'No code-owned active boss damage target; no changes made')
 end
 assert(#plan.notifications&gt;0 and #plan.notifications&lt;=12 and #plan.writes&lt;=64,'Unexpected boss target count')
 return plan
end
return P
]====]):sub(2),
 [ [====[mgs-boss.lua]====] ]=([====[!-- Boss detection, native health-bar discovery and local recordings. Target reads only.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local D=dofile(dir..'mgs-discovery.lua')
local B={pid=R.pid,reader=R,bindings={},captures=0,version=1}
local catalog=dofile(dir..'mgs-boss-experimental.lua').catalog
B.catalog=catalog
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xFFFFFFFF end
local function psx(p,n)assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'PSX pointer invalid');return p&amp;0x1FFFFF end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function binary(r,o,n)
 assert(o&gt;=0 and n&gt;=0 and o+n&lt;=0x200000,'Capture outside RAM')
 local out={}
 for j=0,n-1,4096 do local k=math.min(4096,n-j);local t=assert(readBytes(r+o+j,k,true));assert(#t==k);out[#out+1]=string.char(table.unpack(t))end
 return table.concat(out)
end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function isBranch(w)return op(w)==1 or (op(w)&gt;=4 and op(w)&lt;=7)or op(w)==2 or op(w)==3 or (op(w)==0 and ((w&amp;63)==8 or (w&amp;63)==9))end
local function copy(t)local r={};for k,v in pairs(t)do r[k]=v end;return r end
local function destination(w)
 if op(w)==0 then return rd(w)end
 if (op(w)&gt;=8 and op(w)&lt;=15)or (op(w)&gt;=32 and op(w)&lt;=39)then return rt(w)end
end
-- Conservative backwards slice: only a direct work-field load, a move and/or
-- a left shift are accepted. Branches, calls and complex arithmetic reject it.
local function expression(words,aliases,at,reg,depth)
 if (depth or 0)&gt;5 then return nil end
 if reg==0 then return {kind='constant',value=0}end
 for i=at,math.max(1,at-24),-1 do
  local w=words[i];if isBranch(w)then return nil end
  if destination(w)==reg then
   if op(w)==35 then
    local base=aliases[i][rs(w)]
    if base~=nil and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     local offset=base+signed(w&amp;0xFFFF)
     if offset&gt;=0x20 and offset&lt;=0x4000 and offset%4==0 then return {kind='field',offset=offset,scale=1}end
    end
   elseif op(w)==9 and rs(w)==0 then return {kind='constant',value=signed(w&amp;0xFFFF)}
   elseif op(w)==13 and rs(w)==0 then return {kind='constant',value=w&amp;0xFFFF}
   elseif op(w)==0 then
    local f=w&amp;63
    if (f==33 or f==37)and (rs(w)==0 or rt(w)==0)then
     return expression(words,aliases,i-1,rs(w)==0 and rt(w)or rs(w),(depth or 0)+1)
    elseif f==0 and rs(w)==0 then
     local e=expression(words,aliases,i-1,rt(w),(depth or 0)+1);local shift=(w&gt;&gt;6)&amp;31
     if e and shift&lt;=4 then if e.kind=='field'then e.scale=e.scale*(1&lt;&lt;shift)else e.value=e.value*(1&lt;&lt;shift)end;return e end
    end
   end
   return nil
  end
 end
end
local function proof(r)
 local a=binary(r,0x3B0A0,24)
 local b=binary(r,0x3B10C,24)
 return a==string.char(0xD8,0xFF,0xBD,0x27,0x21,0x40,0x80,0,0x21,0x48,0xA0,0,0x21,0x50,0xC0,0,0,4,3,0x24,0x21,0x28,0,1)
  and b==string.char(0xE0,0xFF,0xBD,0x27,0x21,0x18,0x80,0,0x21,0x40,0xA0,0,0x21,0x48,0xC0,0,0x0A,0x80,4,0x3C,0x1C,0x0A,0x84,0x24)
end
function B.discoverBar(r,actor)
 if not proof(r)then return nil,'Resident health-bar wrapper fingerprint differs'end
 local queue={actor.act};local visited={};local found={};local count=0
 while #queue&gt;0 and count&lt;24 do
  local fn=table.remove(queue,1)
  if not visited[fn]and fn&gt;=0x800C0000 and fn&lt;0x801F0000 and fn%4==0 then
   visited[fn]=true;count=count+1
   local code=binary(r,psx(fn),math.min(0x600,0x200000-psx(fn)));local words={};local aliases={};local alias={[4]=0}
   local stop=false
   for i=1,#code//4 do
    local w=string.unpack('&lt;I4',code,(i-1)*4+1);words[i]=w;aliases[i]=copy(alias)
    -- The previous instruction's call has this instruction as its delay slot.
    local prior=words[i-1]
    local dest=destination(w);local v
    if op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if rt(w)==0 then v=alias[rs(w)]elseif rs(w)==0 then v=alias[rt(w)]end
    elseif op(w)==9 and alias[rs(w)]~=nil then v=alias[rs(w)]+signed(w&amp;0xFFFF)end
    if dest and dest~=0 then alias[dest]=v end
    if prior and op(prior)==3 then
     local callee=((prior&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if callee==0x8003B0A0 or callee==0x8003B10C then
      -- Exclude the JAL itself from the backwards slice, but include a
      -- register assignment in its delay slot when present.
      local arg=callee==0x8003B0A0 and 7 or 6
      local e
      if destination(w)==arg then
       local short={w};local aa={aliases[i]};e=expression(short,aa,1,arg)
       if not e and op(w)==0 and (w&amp;63)==0 then
        local source=expression(words,aliases,i-2,rt(w));local shift=(w&gt;&gt;6)&amp;31
        if source and source.kind=='field'and shift&lt;=4 then source.scale=source.scale*(1&lt;&lt;shift);e=source end
       elseif not e and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)and (rs(w)==0 or rt(w)==0)then
        e=expression(words,aliases,i-2,rs(w)==0 and rt(w)or rs(w))
       end
      else e=expression(words,aliases,i-2,arg)end
      local maximum=1024
      if callee==0x8003B10C then
       local mx=destination(w)==7 and expression({w},{aliases[i]},1,7)or expression(words,aliases,i-2,7)
       if not mx or mx.kind~='constant'or mx.value~=1024 then maximum=nil end
      end
      if e and e.kind=='field'and e.scale&lt;=16 and maximum then
       local key=e.offset..':'..e.scale;found[key]={offset=e.offset,scale=e.scale,maximum=maximum,callPC=fn+(i-2)*4,fn=fn}
      end
     elseif alias[4]==0 and callee&gt;=0x800C0000 and callee&lt;0x801F0000 then queue[#queue+1]=callee end
     for j=2,15 do alias[j]=nil end;alias[24]=nil;alias[25]=nil
    end
    if stop then break end
    if op(w)==0 and (w&amp;63)==8 and rs(w)==31 then stop=true end
   end
  end
 end
 local list={};for _,v in pairs(found)do list[#list+1]=v end
 if #list~=1 then return nil,'Health-bar field not uniquely resolved ('..#list..')'end
 return list[1]
end
function B.actors(r)
 local ok,root=pcall(D.actorRoot,r)
 if not ok then
  -- Liquid uses a different Snake actor. Validate the resident list sentinels
  -- rather than guessing its CONTROL-to-actor offset from the normal Snake.
  root=0xAF390
  for level=0,8 do
   local s=root+level*0x44;local e=s+0x20
   assert(u32(r+s)==0 and u32(r+s+8)==0 and u32(r+s+12)==0 and u32(r+e+4)==0 and u32(r+e+8)==0 and u32(r+e+12)==0,'Actor-list root unavailable')
   psx(u32(r+s+4),32);psx(u32(r+e),32)
  end
 end
 local out={}
 for level=0,8 do
  local start=root+level*0x44;local finish=start+0x20;local previous=start;local p=u32(r+start+4);local seen={}
  for n=1,512 do
   local o=psx(p,32)
   if o==finish then assert(u32(r+finish)==0x80000000+previous,'Actor tail changed');break end
   assert(not seen[o],'Actor cycle');seen[o]=true
   assert(u32(r+o)==0x80000000+previous,'Actor list changed')
   local act,die,np=u32(r+o+8),u32(r+o+12),u32(r+o+20)
   if act&gt;=0x800C0000 and act&lt;0x80200000 and die&gt;=0x800C0000 and die&lt;0x80200000 and np&gt;=0x80000000 and np&lt;0x80200000 then
    out[#out+1]={offset=o,act=act,die=die,name=readString(r+psx(np),48),level=level}
   end
   previous=o;p=u32(r+o+4);assert(n&lt;512,'Actor limit')
  end
 end
 return out
end
function B.ownership(r,actor)
 assert(binary(r,0x2ECCC,24)==string.char(0x0C,0x80,3,0x3C,0x48,0x8C,0x63,0x24,0x2B,0x10,3,2,4,0,0x40,0x14,0,0x12,0x62,0x24,0x2B,0x10,2,2),'Resident TARGET pool differs')
 local e={targets={},fields={},proofs={},functions=0,blocks={}}
 local overlay=binary(r,0xC0000,0xA0000)
 local queue={{fn=actor.die,base=0},{fn=actor.act,base=0}};local seen={}
 local function mark(field,kind,pc,w)
  if field&lt;0x20 or field&gt;0x4000 then return end
  local v=e.fields[field]or {};e.fields[field]=v;v[kind]={pc=pc,word=w}
 end
 while #queue&gt;0 and e.functions&lt;128 do
  local item=table.remove(queue,1);local fn,base=item.fn,item.base;local key=tostring(fn)..':'..tostring(base)
  if item.aliases then for reg=1,31 do if item.aliases[reg]~=nil then key=key..':'..reg..'='..item.aliases[reg]end end end
  if not seen[key]and fn&gt;=0x800C0000 and fn&lt;0x80160000 and fn%4==0 then
   seen[key]=true;e.functions=e.functions+1
   local offset=(fn&amp;0x1FFFFF)-0xC0000
   local code=overlay:sub(offset+1,offset+0x1000);local words,aliases={},{};local alias=item.aliases or {[4]=base};local loaded={};local stop=false
   for i=1,#code//4 do
    local w=string.unpack('&lt;I4',code,(i-1)*4+1);local pc=fn+(i-1)*4;words[i]=w;aliases[i]=copy(alias)
    local o=op(w);local field=alias[rs(w)]and alias[rs(w)]+signed(w&amp;0xFFFF)
    if field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     if o==35 then mark(field,'read',pc,w);loaded[rt(w)]={field=field}
     elseif o==43 then mark(field,'write',pc,w);if loaded[rt(w)]and loaded[rt(w)].field==field and loaded[rt(w)].decrement then mark(field,'decrement',pc,w)end end
    end
    if o==35 and not(field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23)))then loaded[rt(w)]=nil end
    local dest=destination(w);local value
    if o==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if rt(w)==0 then value=alias[rs(w)]elseif rs(w)==0 then value=alias[rt(w)]end
    elseif o==9 and alias[rs(w)]~=nil then value=alias[rs(w)]+signed(w&amp;0xFFFF)end
    if o==9 and rt(w)==rs(w)and signed(w&amp;0xFFFF)==-1 and loaded[rt(w)]then loaded[rt(w)].decrement=true
    elseif dest and dest~=0 and o~=35 then loaded[dest]=nil end
    if dest and dest~=0 then alias[dest]=value end
    local prior=words[i-1]
    if prior and (op(prior)==3 or op(prior)==2)then
     local callee=((prior&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if callee==0x8002ECB8 then
      local exp
      if destination(w)==4 then
       exp=expression({w},{aliases[i]},1,4)
       if not exp and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)and (rs(w)==0 or rt(w)==0)then exp=expression(words,aliases,i-2,rs(w)==0 and rt(w)or rs(w))end
      else exp=expression(words,aliases,i-2,4)end
      if exp and exp.kind=='field'and exp.scale==1 then e.targets[exp.offset]={field=exp.offset,pc=pc-4,word=prior}end
     elseif callee&gt;=0x800C0000 and callee&lt;0x80160000 then
      if op(prior)==2 then
       -- Follow a real unconditional control-flow edge, preserving its work
       -- aliases. Do not fall through into the next unrelated function.
       queue[#queue+1]={fn=callee,aliases=copy(alias)}
      elseif alias[4]and alias[4]&gt;=0 and alias[4]&lt;0x4000 then queue[#queue+1]={fn=callee,base=alias[4]}end
     end
     for j=2,15 do alias[j]=nil;loaded[j]=nil end;alias[24]=nil;alias[25]=nil
    end
    if stop then break end
    if o==2 or (o==0 and (w&amp;63)==8 and rs(w)==31)then stop=true end
   end
   e.blocks[#e.blocks+1]={address=r+(fn&amp;0x1FFFFF),bytes=code:sub(1,#words*4)}
  end
 end
 return e
end
local function matches(r,offset,hex)
 local expected=hex:gsub('%x%x',function(h)return string.char(tonumber(h,16))end)
 return binary(r,offset,#expected)==expected
end
-- Ocelot's observed installed-build layout, corroborated by the damage-to-bar
-- calculation, seven-state dispatcher, counter increment and cylinder refill.
-- Checks are relative to his discovered Act address, never the actor allocation.
function B.ocelot(r,a,b)
 if not b.binding or b.binding.offset~=0x854 or b.binding.scale~=1 then return end
 local fn=psx(a.act)
 if fn&lt;0x1EDC then return end
 if not matches(r,fn-0x1EDC,'3C08028E00000000260044846009038E801204001A004300')then return end
 local target=u32(r+a.offset+0x83C);local to=psx(target,0x48)
 local hp=assert(readSmallInteger(r+to+0x26))&amp;0xFFFF;if hp&gt;=32768 then hp=hp-65536 end
 local maximum=s32(r+a.offset+0x960)
 if maximum&gt;0 and maximum&lt;=32767 and hp&gt;=0 and hp&lt;=maximum and b.bar and math.abs(math.floor(hp*1024/maximum)-b.bar)&lt;=8 then
  b.hp=hp;b.maxHP=maximum;b.target=target
 end
 if matches(r,fn-0x3BC,'FC08038E000000000700622C28004010')then
  local phase=s32(r+a.offset+0x8FC)
  if phase&gt;=0 and phase&lt;=6 then
   local names={[0]='Combat / positioning',[1]='Combat movement',[2]='Firing',[3]='RELOADING',[4]='Defeated',[5]='Combat transition',[6]='Opening'}
   b.phaseID=phase;b.phase=names[phase]..' ('..phase..')';b.phaseEvidence='Firing/reload confirmed in gameplay'
  end
 end
 if matches(r,fn-0x560,'0400A28C00000000010042240400A2AC')then
  local counter=s32(r+a.offset+0x900)
  if counter&gt;=0 and counter&lt;=1000000 then b.stateCounter=counter end
 end
 if matches(r,fn-0x7AC,'06000224740802AE780800AE')then
  local rounds=s32(r+a.offset+0x874)
  if rounds&gt;=0 and rounds&lt;=6 then b.rounds=rounds;b.cylinder=6 end
 end
 b.evidence='Ocelot health, cylinder and reload validated; HP/layout checked in code'
end
function B.inspect()
 local h=R.read();local r=h.ram
 assert(u32(r+0xADB40)==0 and u32(r+0xAE1B0)~=0,'Area loading; previous boss readings cleared')
 local stage=readString(r+0xB7500,16)or '?'
 local all=B.actors(r);local c={ram=r,stage=stage,playerHealth=h.health,actors=all,bosses={}}
 for _,a in ipairs(all)do
  local p=catalog[a.name]
  if p and p.stages[stage]then
   local b={name=p.name,actor=a,phase='Not mapped',attackTimer='Not mapped',evidence='Not gameplay-validated'}
   local key=string.format('%X:%s:%X:%X',r,stage,a.offset,a.act)
   local signature=binary(r,psx(a.act),32)
   local cache=B.bindings[key]
   local changed=cache and cache.binding and binary(r,psx(cache.binding.callPC)-96,104)~=cache.callSignature
   if not cache or cache.signature~=signature or changed or not proof(r)then
    local binding,why=B.discoverBar(r,a);cache={binding=binding,why=why,signature=signature};B.bindings[key]=cache
    if binding then cache.callSignature=binary(r,psx(binding.callPC)-96,104)end
   end
   b.binding=cache.binding;b.reason=cache.why
   if b.binding then
    local raw=s32(r+a.offset+b.binding.offset);local now=raw*b.binding.scale
    if now&gt;=0 and now&lt;=b.binding.maximum then b.bar=now;b.maximum=b.binding.maximum;b.percent=100*now/b.maximum;b.raw=raw
    else b.reason='Resolved value outside health-bar range; reading suppressed'end
   end
   if a.name=='revolver.c'then B.ocelot(r,a,b)end
   -- CONTROL.mov is a signed SVECTOR. Coordinate layout is common to the
   -- validated Snake actor; Ocelot/tank include an extra field before CONTROL.
   local control=(a.name=='revolver.c'or a.name=='m1e1.c')and 0x24 or 0x20
   b.positionCandidate={}
   for j=0,2 do local v=assert(readSmallInteger(r+a.offset+control+j*2))&amp;0xFFFF;b.positionCandidate[j+1]=v&gt;=32768 and v-65536 or v end
   c.bosses[#c.bosses+1]=b
  end
 end
 return c
end
function B.capture(c,b)
 assert(B.captures&lt;8,'Eight-capture limit reached; start a new dashboard session for more')
 local a=b.actor;assert(u32(c.ram+a.offset+8)==a.act and u32(c.ram+a.offset+12)==a.die,'Boss actor changed')
 B.captures=B.captures+1
 local stem=dir..'../logs/boss-'..B.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'-'..B.captures
 local function write(suffix,data)local f=assert(io.open(stem..suffix,'wb'));local ok,err=f:write(data);f:close();assert(ok,err)end
 write('-actor.bin',binary(c.ram,a.offset,math.min(0x3000,0x200000-a.offset)))
 write('-overlay.bin',binary(c.ram,0xC0000,0xA0000))
 write('.txt',string.format('Read-only boss capture\nPID=%d\nStage=%s\nBoss=%s\nActor=%08X\nAct=%08X\nDie=%08X\nHealth=%s / %s\nEvidence=%s\nActor file is a bounded memory window, not an allocation-size claim.\n',B.pid,c.stage,b.name,0x80000000+a.offset,a.act,a.die,tostring(b.bar),tostring(b.maximum),b.evidence))
 B.lastCapture=stem;return stem
end
return B
]====]):sub(2),
 [ [====[mgs-cosmetic-colors.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- Session-only US Snake render tint. Native reference: libdg/shade.c,
-- equip/kogaku2.c. No texture, geometry, inventory or game-code edits.
local options=(...)or{}
assert(options.detached or not MGSColorTest,'Retain existing color binding for restore')
local C={version=1}
local function u32(a)return assert(readInteger(a))&amp;0xffffffff end
local function context()
 local c=options.context and options.context()or MGSCosmeticTest.context()
 local parts={}
 for i=0,15 do
  local o=c.object+0x48+i*0x5c
  assert(u32(o+0x48)==0,'Extended model unsupported')
  local n=assert(readSmallInteger(o+0x52))&amp;0xffff
  local m=c.definition+0x20+i*0x58
  assert(u32(o+0x40)==0x80000000+(m-c.ram),'Model owner differs')
  assert(n==u32(m+4) and n&gt;0 and n&lt;=100,'Packet count differs')
  for k=0,1 do
   local p=u32(o+0x54+k*4)
   assert(p&gt;=0x80010000 and p+n*52&lt;=0x80200000,'Packet buffer outside RAM')
   parts[#parts+1]={index=i,address=c.ram+(p&amp;0x1fffff),count=n}
  end
 end
 c.parts=parts;return c
end
local function same(a,b)
 assert(a.ram==b.ram and a.work==b.work and a.object==b.object and a.definition==b.definition,'Snake owner changed')
 for i,p in ipairs(a.parts)do local q=b.parts[i];assert(p.address==q.address and p.count==q.count,'Packet buffers changed')end
end
local presets={red={1.8,0.22,0.12},green={0.18,1.5,0.22},black={0.14,0.14,0.14},
 yellow={1.6,1.5,0.12},cyan={0.12,1.5,1.6},blue={0.18,0.22,1.8},magenta={1.7,0.12,1.7}}
function C.apply(name)
 local rgb=assert(presets[name],'Unknown suit tint')
 local c=context()
 if not C.binding then
  assert(u32(c.object+0x28)==0x32d,'Unexpected render flags; remove other effects first')
  local b={context=c,colors={}}
  for _,p in ipairs(c.parts)do for n=0,p.count-1 do for _,off in ipairs({4,16,28,40})do
   local a=p.address+n*52+off
   local command=readBytes(a+3,1,false)
   assert(command==0x3c,string.format('Unexpected primitive command at part%d address%X: %s',p.index,a,tostring(command)))
   local v=assert(readBytes(a,3,true));b.colors[#b.colors+1]={address=a,original=v,suit=p.index~=4 and p.index~=5 and p.index~=6 and p.index~=9}
  end end end
  same(c,context());C.binding=b
 else same(C.binding.context,c);assert((u32(c.object+0x28)&amp;8)==0,'Native shading resumed; restore first')end
 local b=C.binding
 assert(writeInteger(c.object+0x28,u32(c.object+0x28)&amp;(~8)),'Could not disable shading')
 for _,p in ipairs(b.colors)do
  local v=p.original
  if p.suit then
   local light=math.max(v[1],v[2],v[3]);v={}
   for i=1,3 do v[i]=math.min(255,math.floor(light*rgb[i]+0.5))end
  end
  assert(writeBytes(p.address,v),'Tint write interrupted; retain binding')
 end
 C.status=name..' suit tint active';return C.status
end
function C.restore()
 if C.timer then C.timer.destroy();C.timer=nil end
 local b=C.binding;if not b then return true end
 local c=context();same(b.context,c)
 for _,p in ipairs(b.colors)do assert(writeBytes(p.address,p.original),'Color restore interrupted')end
 assert(writeInteger(c.object+0x28,u32(c.object+0x28)|8),'Shading restore interrupted')
 C.binding=nil;C.status='Native shading restored';return C.status
end
function C.startRainbow()
 assert(not C.timer,'Rainbow already running')
 local sequence={'red','yellow','green','cyan','blue','magenta'}
 C.apply(sequence[1]);C.rainbowStep=1;C.rainbowTicks=0
 local timer=createTimer(nil,false);C.timer=timer;timer.Interval=400
 timer.OnTimer=function()
  local ok,err=pcall(function()
   C.rainbowTicks=C.rainbowTicks+1
   if C.rainbowTicks&gt;=150 then C.restore();return end
   C.rainbowStep=C.rainbowStep%#sequence+1
   C.apply(sequence[C.rainbowStep])
  end)
  if not ok then
   if C.timer then C.timer.destroy();C.timer=nil end
   C.status='Rainbow stopped: '..tostring(err)
   -- Restore only through the same full context/ownership validation.
   local restored=pcall(C.restore)
   if not restored then C.status=C.status..'; restore pending valid gameplay' end
  end
 end
 timer.Enabled=true
 return 'Rainbow preview active for60 seconds; 400ms per color'
end
if not options.detached then MGSColorTest=C end
return C
]====]):sub(2),
 [ [====[mgs-discovery.lua]====] ]=([====[!-- Read-only discovery of resident actor lists and relocated overlay parameters.
local D={version=1,root=nil}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xFFFFFFFF end
local function offset(p,n)
 assert(p and p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'Invalid PSX pointer')
 return p&amp;0x1FFFFF
end
local function header(ram,o)
 local b=assert(readBytes(ram+o,32,true),'Actor header unavailable')
 assert(#b==32,'Short actor header')
 local function w(i)return b[i+1]|(b[i+2]&lt;&lt;8)|(b[i+3]&lt;&lt;16)|(b[i+4]&lt;&lt;24)end
 return {offset=o,prev=w(0),next=w(4),act=w(8),die=w(12),namePointer=w(20)}
end
local function rootsValid(ram,root)
 if not root or root&lt;0x10000 or root+9*0x44&gt;0x200000 then return false end
 for i=0,8 do
  local s=header(ram,root+i*0x44);local e=header(ram,root+i*0x44+0x20)
  if s.prev~=0 or s.act~=0 or s.die~=0 or e.next~=0 or e.act~=0 or e.die~=0 then return false end
 end
 return true
end
function D.actorRoot(ram)
 if D.root and rootsValid(ram,D.root)then return D.root end
 local p=offset(u32(ram+0xAE16C),0x100)-0x20
 local seen={}
 for _=1,512 do
  assert(not seen[p],'Actor predecessor cycle');seen[p]=true
  local h=header(ram,p)
  if h.prev==0 then
   local roots={}
   for level=0,8 do local r=p-level*0x44;if rootsValid(ram,r)then roots[#roots+1]=r end end
   assert(#roots==1,'Actor-list root not uniquely identified');D.root=roots[1];return D.root
  end
  p=offset(h.prev,32)
 end
 error('Actor predecessor chain exceeds limit')
end
function D.actors(ram)
 local root=D.actorRoot(ram);local start=root+4*0x44;local finish=start+0x20
 local previous=start;local pointer=u32(ram+start+4);local result={};local seen={}
 for _=1,512 do
  local o=offset(pointer,32)
  if o==finish then
   assert(u32(ram+finish)==0x80000000+previous,'Actor tail changed during enumeration')
   return result
  end
  assert(not seen[o],'Actor-list cycle');seen[o]=true
  local h=header(ram,o)
  assert(h.prev==0x80000000+previous,'Actor list changed while reading')
  if h.act&gt;=0x800C0000 and h.act&lt;0x80200000 and h.die&gt;=0x800C0000 and h.die&lt;0x80200000 then
   local ok,n=pcall(function()return readString(ram+offset(h.namePointer,1),48)end)
   if ok and n then h.name=n;result[#result+1]=h end
  end
  previous=o;pointer=h.next
 end
 error('Actor count exceeds limit')
end
local function binary(ram,start,size)
 local parts={}
 for o=0,size-1,8192 do
  local n=math.min(8192,size-o);local b=assert(readBytes(ram+start+o,n,true),'Overlay read unavailable')
  assert(#b==n,'Short overlay read');parts[#parts+1]=string.char(table.unpack(b))
 end
 return table.concat(parts)
end
function D.overlay(ram)
 local code={start=0xC0000,size=0xA0000}
 code.bytes=binary(ram,code.start,code.size)
 function code.word(o)
  if o&lt;code.start or o+4&gt;code.start+code.size or o%4~=0 then return nil end
  return string.unpack('&lt;I4',code.bytes,o-code.start+1)
 end
 return code
end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function imm(w)local n=w&amp;0xFFFF;return n&gt;=32768 and n-65536 or n end
local function absolute(code,p,w)
 local base=rs(w)
 for back=1,3 do
  local h=code.word(p-back*4)
  if h and op(h)==15 and rt(h)==base then
   local a=((h&amp;0xFFFF)&lt;&lt;16)+imm(w)
   if a&gt;=0x800C0000 and a&lt;0x80200000 then return a&amp;0x1FFFFF end
  end
 end
end
local function guardGateProof(code)
 local found={}
 for p=code.start,code.start+code.size-12,4 do
  local w=code.word(p)
  if (op(w)==36 or op(w)==32)and (w&amp;0xFFFF)==0xBA3 then
   for j=1,2 do
    local a=code.word(p+4*j)
    if a and op(a)==12 and rs(a)==rt(w)then found[a&amp;0xFFFF]=true end
   end
  end
 end
 return found[1]and found[4]and found[16]
end
function D.reachable(code,entry)
 local pending={entry&amp;0x1FFFFF};local head=1;local seen={};local words={};local functions=0
 while head&lt;=#pending and functions&lt;180 do
  local fn=pending[head];head=head+1
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;functions=functions+1
   for p=fn,math.min(fn+0x2000,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if op(w)==3 then
     local target=((w&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if target&gt;=0x800C0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1FFFFF end
    end
    if w==0x03E00008 then words[p+4]=code.word(p+4);break end
   end
  end
 end
 return words
end
function D.guardProfile(ram,actors,code)
 local watchers={};for _,a in ipairs(actors)do if a.name=='watcher.c'then watchers[a.offset]=a end end
 if not next(watchers)then return nil,'No standard guards loaded' end
 if not guardGateProof(code)then return nil,'Guard sensing layout not recognized'end
 local first=next(watchers);local reachable=D.reachable(code,watchers[first].act)
 local eyes={}
 for p=code.start+12,code.start+code.size-8,4 do
  local w=code.word(p);local after=code.word(p+4)
  if reachable[p]and op(w)==9 and (w&amp;0xFFFF)==2000 and rs(w)==rt(w)and after and op(after)==0 and (after&amp;63)==42 and rs(after)==rt(w)then
   for back=1,3 do
    local q=code.word(p-back*4)
    if q and op(q)==35 and rt(q)==rt(w)then local eye=absolute(code,p-back*4,q);if eye then eyes[eye]=p end;break end
   end
  end
 end
 local matches={}
 for eye,visionPC in pairs(eyes)do
  local configs={};local shoot
  for p=code.start+12,code.start+code.size-52,4 do
   local w=code.word(p)
   if op(w)==33 then
    local address=absolute(code,p,w)
    if address then
     for j=1,6 do
      local q=code.word(p+4*j)
      if q and op(q)==43 and rt(q)==rt(w)and absolute(code,p+4*j,q)==eye then
       local add=code.word(p+4*j+4)
       if add and op(add)==9 and rt(add)==rt(w)and rs(add)==rt(w)and (add&amp;0xFFFF)==500 then
        configs[address]=true
        for k=2,5 do
         local z=code.word(p+4*(j+k))
         if z and op(z)==43 and rt(z)==rt(w)then local dst=absolute(code,p+4*(j+k),z);if dst==eye-4 then shoot=dst end end
        end
       end
      end
     end
    end
   end
  end
  for first in pairs(configs)do
   if configs[first+2]and configs[first+4]and shoot then
    local command=first-0x88
    local count=u32(ram+command+8);local mode=u32(ram+command+0x18);local seen=0;local valid=true
    if count&gt;8 or mode&gt;2 then valid=false end
    if valid then
     for i=0,7 do
      local p=u32(ram+command+0xC8+i*0x10+0xC)
      if p~=0 and p&gt;=0x80000000 and p&lt;0x80200000 then
       local g=watchers[p&amp;0x1FFFFF]
       if g and readBytes(ram+g.offset+0xB78,1)==i then seen=seen+1 end
      end
     end
     if seen&gt;0 then matches[#matches+1]={command=command,eye=eye,shoot=shoot,ranges=first,visionPC=visionPC,matched=seen}end
    end
   end
  end
 end
 if #matches~=1 then return nil,'Guard range/commander mapping is not unique ('..#matches..')'end
 return matches[1]
end
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
function D.cameraProfile(actor,code)
 if not cameraNames[actor.name]then return nil end
 local pending={actor.act&amp;0x1FFFFF};local seen={};local candidates={};local examined=0
 while #pending&gt;0 and examined&lt;100 do
  local fn=table.remove(pending)
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;examined=examined+1
   local words={};local workRegisters={}
   for p=fn,math.min(fn+0x1800,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if p&lt;fn+0x60 and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if (rs(w)==4 and rt(w)==0)or(rs(w)==0 and rt(w)==4)then workRegisters[rd(w)]=true end
    end
    if op(w)==3 then
     local target=((w&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if target&gt;=0x800C0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1FFFFF end
    end
    if w==0x03E00008 then words[p+4]=code.word(p+4);break end
   end
   for p,w in pairs(words)do
    if op(w)==3 and (((w&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000)==0x80017494 then
     for j=1,7 do
      local compare=words[p+j*4]
      if compare and op(compare)==0 and (compare&amp;63)==42 and rt(compare)==2 then
       local rangeRegister=rs(compare)
       for back=p+j*4-4,math.max(fn,p-0x40),-4 do
        local load=words[back]
        if load and (op(load)==37 or op(load)==35)and rt(load)==rangeRegister and workRegisters[rs(load)]then
         local field=load&amp;0xFFFF;local size=op(load)==37 and 2 or 4
         if field&gt;=0x100 and field&lt;0x800 then
          local width=false
          for q,z in pairs(words)do if q&lt;p and op(z)==op(load)and rs(z)==rs(load)and (z&amp;0xFFFF)==field+size then width=true end end
          if width then candidates[field]={range=field,size=size,detector=fn,loadPC=back}end
         end
         break
        end
       end
      end
     end
    end
   end
  end
 end
 local profiles={};for _,v in pairs(candidates)do profiles[#profiles+1]=v end
 if #profiles~=1 then return nil,'Camera distance check is not unique ('..#profiles..')'end
 return profiles[1]
end
function D.guardActors(ram,actors,profile)
 local result={};if not profile then return result end
 local present={};for _,a in ipairs(actors)do present[a.offset]=a end
 for i=0,7 do
  local p=u32(ram+profile.command+0xC8+i*0x10+0xC)
  if p&gt;=0x80000000 and p&lt;0x80200000 then
   local a=present[p&amp;0x1FFFFF]
   if a and a.name=='watcher.c'and readBytes(ram+a.offset+0xB78,1)==i then a.slot=i;result[a.offset]=a end
  end
 end
 return result
end
return D
]====]):sub(2),
 [ [====[mgs-fun-context.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- Shared read-only normal-US-Snake render ownership checks.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local G=dofile(dir..'mgs-inventory.lua')
local A=dofile(dir..'mgs-aura-render.lua')
local F={pid=getOpenedProcessID()}
local function u32(a)return assert(readInteger(a))&amp;0xffffffff end
local function u16(a)return assert(readSmallInteger(a))&amp;0xffff end
local function ptr(r,p,n)assert(p&gt;=0x80010000 and p+n&lt;=0x80200000,'Render pointer outside RAM');return r+(p&amp;0x1fffff)end
local function hash(s)local n=0;for i=1,#s do n=(((n&lt;&lt;5)|(n&gt;&gt;11))+s:byte(i))&amp;0xffff end;return n end
function F.read()
 assert(getOpenedProcessID()==F.pid,'Attached process changed')
 local c=G.context(true);local r=c.ram
 assert(c.stage:match('^s%d%d%lr?$'),'Enter a normal story stage')
 assert(u32(r+0xAE0A0)==0 and u32(r+0xBFAD0)==0x8003A948 and u32(r+0xBFAD4)==0x8003AA94 and u16(r+0xBFAF2)==0,'Resume normal gameplay and close menus')
 local id=hash(c.stage)
 assert(readString(r+0xADB34,8)==c.stage and u16(r+0xAE138)==id and u16(r+0xB751C)==id and u16(r+0xB7FC8)==id,'Stage transition in progress')
 assert(c.activeGadget~=10 and c.activeGadget~=5 and c.activeGadget~=6,'Remove stealth or vision goggles before cosmetics')
 c.object=ptr(r,u32(r+c.work+0x9c),0x48+16*0x5c)
 assert(u16(c.object+0x2e)==16,'Normal Snake model required')
 c.definition=ptr(r,u32(c.object+0x24),0x20+16*0x58)
 assert(u32(c.definition)==16,'Snake definition differs')
 local q=A.queueState(r);local present=false
 for i=0,q.objs-1 do if u32(r+A.queue+i*4)==0x80000000+c.object-r then present=true end end
 assert(present,'Snake body is not in the renderer queue')
 return c
end
return F
]====]):sub(2),
 [ [====[mgs-fun-stuff.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- Persistent guarded big-head and suit-color choices; normal US Snake only.
local prior=MGSFunStuff
if prior and prior.pid==getOpenedProcessID()then return prior end
if prior and prior.timer then prior.timer.destroy();prior.timer=nil end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local F=dofile(dir..'mgs-fun-context.lua')
local H=assert(loadfile(dir..'mgs-big-head.lua'))({detached=true,context=F.read})
local C=assert(loadfile(dir..'mgs-cosmetic-colors.lua'))({detached=true,context=F.read})
local T={pid=getOpenedProcessID(),head=H,colors=C,requestedHead=false,status='Off'}
local function u32(a)return assert(readInteger(a))&amp;0xffffffff end
local function headOwner(a,b)return a.ram==b.ram and a.work==b.work and a.stage==b.stage and a.object==b.object and a.definition==b.definition and a.model==b.model and a.vertices==b.vertices end
local function colorOwner(c)
 local b=C.binding;if not b then return false end;local old=b.context
 if old.ram~=c.ram or old.work~=c.work or old.stage~=c.stage or old.object~=c.object or old.definition~=c.definition then return false end
 for i,p in ipairs(old.parts)do
  if c.ram+(u32(c.object+0x48+p.index*0x5c+0x54+((i-1)%2)*4)&amp;0x1fffff)~=p.address then return false end
 end
 return true
end
local function atomic(fn)
 pause();local ok,result=pcall(fn);unpause();if not ok then error(result)end;return result
end
function T.tick()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local c=F.read()
 if H.binding then
  local now=H.context()
  if not headOwner(H.binding.context,now)then H.binding=nil end
 end
 if T.requestedHead and not H.binding then H.apply(1.8)
 elseif not T.requestedHead and H.binding then H.restore()end
 if C.binding and (not colorOwner(c)or u32(c.object+0x28)&amp;8~=0)then C.binding=nil end
 if T.requestedColor then
  assert(not MGSSuperRainbow or not MGSSuperRainbow.enabled,'Switch Super Saiyan off before a single suit color')
  if not C.binding or T.appliedColor~=T.requestedColor then C.apply(T.requestedColor);T.appliedColor=T.requestedColor end
 elseif C.binding then C.restore();T.appliedColor=nil end
 if not T.requestedHead and not T.requestedColor and not H.binding and not C.binding then
  if T.timer then T.timer.destroy();T.timer=nil end
 end
 T.status='Big head '..(T.requestedHead and 'ON'or 'OFF')..'; suit '..(T.requestedColor or 'native')
 return T.status
end
local function ensureTimer()
 if T.timer then return end
 local timer=createTimer(nil,false);T.timer=timer;timer.Interval=200
 timer.OnTimer=function()
  local ok,err=pcall(function()atomic(T.tick)end)
  if not ok then T.status='Waiting / guarded refusal: '..tostring(err)end
 end
 timer.Enabled=true
end
function T.enable(kind)
 assert(kind=='head'or kind=='red'or kind=='green'or kind=='black','Unknown cosmetic')
 if kind~='head'then assert(not MGSSuperRainbow or not MGSSuperRainbow.enabled,'Disable Super Saiyan before a suit color')end
 if kind=='head'then T.requestedHead=true else T.requestedColor=kind end
 ensureTimer()
 local ok,err=pcall(function()atomic(T.tick)end)
 if not ok then T.status='Waiting / guarded refusal: '..tostring(err)end
 return T.status
end
function T.disable(kind)
 if kind=='head'then T.requestedHead=false elseif T.requestedColor==kind then T.requestedColor=nil end
 ensureTimer()
 local ok,err=pcall(function()atomic(T.tick)end)
 if not ok then T.status='Restore waiting for valid gameplay: '..tostring(err)end
 return T.status
end
MGSFunStuff=T
return T
]====]):sub(2),
 [ [====[mgs-guard-proximity.lua]====] ]=([====[!-- CE-side proximity modes for standard guards: knockout or kill.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSGuardProximity and MGSGuardProximity.pid==getOpenedProcessID()and MGSGuardProximity.version==5 then return MGSGuardProximity end
if MGSGuardProximity then MGSGuardProximity.stop()end
local A=dofile(dir..'mgs-guard-state.lua')
local C={version=5,pid=A.pid,actions=A,enabled=false,mode=nil,radius=A.validateRadius(MGSProximityRadius or 3000),affected=0,batches=0,status='Proximity OFF'}
local ids={knockout=10,kill=11}
local prefixes={knockout='Proximity auto knockout',kill='Proximity auto kill'}
local function record(mode)
 local row=getAddressList().getMemoryRecordByID(ids[mode])
 return row and row.Description:find(prefixes[mode],1,true)==1 and row or nil
end
local function now()return getTickCount()end
function C.setRadius(value)
 C.radius=A.validateRadius(value);MGSProximityRadius=C.radius
 C.status=C.enabled and (C.mode..' ON | radius '..C.radius..' | waiting for nearby guards')or ('Proximity OFF | radius '..C.radius)
 return C.radius
end
function C.disable(mode)
 if mode and C.mode~=mode then return true end
 C.enabled=false;C.mode=nil
 if C.timer then C.timer.Enabled=false end
 C.state=nil;C.nextAction=nil;C.epoch=nil;C.nextCheck=nil
 C.status='Proximity OFF | radius '..C.radius
 for _,kind in ipairs({'knockout','kill'})do local row=record(kind);if row and row.Active then row.Active=false end end
 return true
end
local function audit(result)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../logs/guard-proximity-actions.csv','a+'))
  local success,why=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Proximity action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,mode,radius,slot,actor,distance,hp_before,faint_before\n'))end
   for _,g in ipairs(result.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%d,%d,%08X,%.1f,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),C.pid,result.stage,result.mode,result.radius,g.actor.slot,0x80000000+g.actor.offset,g.distance,g.hp,g.faint)))end end
  end)
  f:close();assert(success,why)
 end)
 if not ok then C.logError=tostring(err)end
end
function C.tick()
 if not C.enabled or C.busy then return end
 if getOpenedProcessID()~=C.pid then C.disable();C.status='Stopped: process changed. Re-enable for the new process.';return end
 local time=now();if C.nextCheck and time&lt;C.nextCheck then return end
 C.busy=true
 local ok,err=pcall(function()
  local c=A.nearby(C.radius);C.state=c
  local epoch=c.ram..':'..c.stage
  if C.epoch~=epoch then C.epoch=epoch;C.nextAction=nil end
  C.status=string.format('%s ON | radius %d | %s | %d nearby, %d ready | %d affected',C.mode,C.radius,c.stage,c.inRange,c.nearEligible,C.affected)
  if c.nearEligible&gt;0 and (not C.nextAction or time&gt;=C.nextAction)then
   local result=A.apply(C.mode,{radius=C.radius})
   C.last=result;C.affected=C.affected+result.affected;C.batches=C.batches+1;C.nextAction=now()+1000
   C.status=string.format('%s ON | radius %d | %s | applied to %d guards (%d total)',C.mode,C.radius,result.stage,result.affected,C.affected)
   audit(result)
  end
 end)
 C.busy=false
 if not ok then
  -- Loading, menus, cutscenes, unsupported layouts or moving targets wait for
  -- a new valid context. No stale actor list is used and no dialog steals focus.
  C.state=nil;C.lastError=tostring(err);C.status='Waiting: '..C.lastError;C.nextCheck=now()+1000
 else C.lastError=nil;C.nextCheck=nil end
end
function C.enable(mode)
 assert(ids[mode],'Unknown proximity mode.')
 assert(not C.stopped and getOpenedProcessID()==C.pid,'Reopen proximity controls for this process.')
 if C.enabled and C.mode==mode then return true end
 C.disable();C.mode=mode;C.enabled=true;C.lastError=nil
 if not C.timer then C.timer=createTimer(nil,false);C.timer.Interval=500;C.timer.OnTimer=C.tick end
 -- Enabling the other AA entry must uncheck this entry without stopping the
 -- replacement mode. disable(mode) above is conditional on the current mode.
 C.status=mode..' ON | radius '..C.radius..' | checking every 500 ms'
 C.timer.Enabled=true
 return true
end
function C.stop()
 C.disable();C.stopped=true
 if C.timer then C.timer.destroy();C.timer=nil end
 if MGSGuardProximity==C then MGSGuardProximity=nil end
 return true
end
MGSGuardProximity=C
return C
]====]):sub(2),
 [ [====[mgs-guard-state.lua]====] ]=([====[!-- Optional one-shot outcomes for standard watcher.c guards. No injected calls.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local D=dofile(dir..'mgs-discovery.lua')
local B=dofile(dir..'mgs-boss.lua')
local A={version=2,pid=R.pid,status='Choose a one-shot guard action.'}
local nativeCache
local function u16(a)return assert(readSmallInteger(a),'Guard short unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Guard word unavailable')&amp;0xFFFFFFFF end
local function bytes(a,n)
 local out={};for j=0,n-1,4096 do
  local k=math.min(4096,n-j);local b=assert(readBytes(a+j,k,true),'Guard code unavailable');assert(#b==k)
  out[#out+1]=string.char(table.unpack(b))
 end;return table.concat(out)
end
local function hex(s)return s:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function context()
 assert(getOpenedProcessID()==A.pid,'Attached process changed; reopen the guard panel.')
 local h=R.read();local r=h.ram
 assert(h.health&gt;0 and u32(r+0xADB40)==0 and u32(r+0xAE1B0)~=0 and u32(r+0xADB44)==0,'Wait for living, normal gameplay.')
 assert(u32(r+0xADB3C)&amp;0xD40C0000==0 and u32(r+0xAE1C8)&amp;0x20002084==0,'Finish the scene or restricted action first.')
 local control=u32(r+0xAE16C)
 assert(control&gt;=0x80000020 and control&lt;0x801FF000,'Normal Snake is not loaded.')
 local snake=(control&amp;0x1FFFFF)-0x20
 assert(u32(r+snake+8)==0x8005CE1C and u32(r+snake+12)==0x8005D514 and u32(r+0xAE198)==0x80000000+snake+0x9C,'Snake actor differs.')
 assert(u32(r+0xBFAC8+8)==0x8003A948 and u32(r+0xBFAC8+12)==0x8003AA94 and u16(r+0xBFAC8+0x2A)==0,'Close the game menu first.')
 local stage=assert(readString(r+0xB7500,16))
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Area is not ready.')
 return {ram=r,stage=stage,h=h,snake=snake}
end
local function damageProfile(code)
 -- The same 80-byte prefix was found independently in the saved hangar and
 -- current armory overlays. Resolve relocated switch-table pointers below.
 local header=hex('E0FFBD271000B0AF218080001800BFAF1400B1AF0009118E0000000006002296000000000400423064004010211000003E00229600000000FFFF422400140200031C02000900622C5900401080100300')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'Guard damage handler is missing or ambiguous.')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(fn-code.start+o+1,fn-code.start+o+#hex(s))==hex(s),'Guard damage branches differ.')end
 match(0x54,'21082200');match(0x5C,'000000000800400000000000')
 local hi,lo=assert(code.word(fn+0x50)),assert(code.word(fn+0x58))
 assert(hi&amp;0xFFFF0000==0x3C010000 and lo&amp;0xFFFF0000==0x8C220000,'Guard damage switch differs.')
 local tablePSX=((hi&amp;0xFFFF)&lt;&lt;16)+signed(lo&amp;0xFFFF)
 assert(tablePSX&gt;=0x800C0000 and tablePSX+36&lt;=0x80160000,'Guard switch table outside overlay.')
 local tableOffset=tablePSX&amp;0x1FFFFF
 assert(code.word(tableOffset)==0x80000000+fn+0xE0 and code.word(tableOffset+8)==0x80000000+fn+0x68,'Guard lethal/punch mode mapping differs.')
 match(0x90,'2A002286000000000700401C9C00042601000224DC0802AE')
 match(0x108,'26002286000000000700401C9C00042601000224DC0802AE')
 match(0x19C,'EC0802AEF40800AE700000A670DC000C6C0000A6')
 match(0x1B4,'280020A6060020A6')
 return {fn=fn,tableOffset=tableOffset,code=code.bytes:sub(start,start+0x1D4-1),switch=code.bytes:sub(tableOffset-code.start+1,tableOffset-code.start+36)}
end
local function recoveryProfile(code)
 local header=hex('D8FFBD271800B0AF218080002000BFAF1C00B1AF700B028E2188A00020004234')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'Guard knockout recovery handler differs.')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'Guard knockout timer layout differs.')end
 match(0x100,'5A0B02A6')
 match(0x1B8,'5A0B0286000000002A1051001200401000000000')
 match(0x1CC,'0009038E000000002A006284000000000400401C9C000426840B0296000000002A0062A4')
 return {fn=fn,code=code.bytes:sub(start,start+0x228-1)}
end
function A.inspect(useCache)
 local c=context();local r=c.ram
 local actors=D.actors(r)
 c.guards={};c.eligible=0;c.knockedOut=0;c.dead=0;c.skipped=0;c.total=0
 local identity={};local watchers=0
 for _,a in ipairs(actors)do if a.name=='watcher.c'or a.name=='command.c'then
  identity[#identity+1]=a.name..':'..a.offset..':'..a.act..':'..a.die..':'..bytes(r+(a.act&amp;0x1FFFFF),32)
  if a.name=='watcher.c'then watchers=watchers+1 end
 end end
 if watchers==0 then nativeCache=nil;c.reason='No standard guards loaded';return c end
 table.sort(identity);local key=r..':'..c.stage..':'..table.concat(identity,'|')
 local cached=useCache and nativeCache and nativeCache.key==key and nativeCache or nil
 if cached and bytes(cached.proof.address,32)~=cached.proof.bytes then cached=nil end
 local code=cached and cached.code or D.overlay(r)
 local profile,why
 if cached then profile=cached.profile else profile,why=D.guardProfile(r,actors,code)end
 if not profile then c.reason=why;return c end
 c.profile=profile;c.damage=cached and cached.damage or damageProfile(code);c.recovery=cached and cached.recovery or recoveryProfile(code);c.ownership={}
 c.profileProof={address=r+profile.visionPC-12,bytes=bytes(r+profile.visionPC-12,32)}
 local families=cached and cached.families or {};local reachable=cached and cached.reachable or {};local retained={};local targets={}
 for _,actor in pairs(D.guardActors(r,actors,profile))do
  local w=actor.offset
  assert(actor.name=='watcher.c'and w~=c.snake and w&gt;=0x10000 and w+0xC4C&lt;=0x200000,'Guard ownership differs.')
  local family=actor.act..':'..actor.die;local e=families[family]
  if not e then e=B.ownership(r,actor);assert(e.targets[0x900],'Guard TARGET pointer lacks native ownership proof.');families[family]=e end
  if not retained[family]then c.ownership[#c.ownership+1]=e;retained[family]=true end
  local ptr=u32(r+w+0x900)
  assert(ptr&gt;=0x800B8C48 and ptr&lt;0x800B9E48 and (ptr-0x800B8C48)%0x48==0,'Guard target pool slot differs.')
  assert(not targets[ptr],'Two guards share a damage target.');targets[ptr]=true
  local t=r+(ptr&amp;0x1FFFFF);local hp,faint=u16(t+0x26),u16(t+0x2A)
  assert(u16(t+2)==2,'Guard target is not enemy-owned.')
  local g={actor=actor,pointer=ptr,target=t,hp=hp,faint=faint,class=u16(t),flags=u16(t+6),action=u32(r+w+0x8EC),status=u32(r+w+0xB70)}
  c.total=c.total+1
  if hp==0 or hp&gt;=32768 then g.reason='dead';c.dead=c.dead+1
  elseif faint==0 or faint&gt;=32768 then g.reason='knocked out / recovering';c.knockedOut=c.knockedOut+1
  elseif g.class&amp;4==0 or g.flags&amp;6~=0 or u16(t+0x42)~=0 or u16(r+w+0xC2C)~=0 then g.reason='busy / not accepting damage';c.skipped=c.skipped+1
  else
   local accepts=reachable[g.action]
   if accepts==nil then accepts=g.action&gt;=0x800C0000 and g.action&lt;0x80160000 and D.reachable(code,g.action)[c.damage.fn]~=nil;reachable[g.action]=accepts end
   if accepts then g.eligible=true;c.eligible=c.eligible+1
   else g.reason='current action has no verified damage path';c.skipped=c.skipped+1 end
  end
  c.guards[#c.guards+1]=g
 end
 table.sort(c.guards,function(a,b)return a.actor.slot&lt;b.actor.slot end)
 nativeCache={key=key,code=code,profile=profile,damage=c.damage,recovery=c.recovery,proof=c.profileProof,families=families,reachable=reachable}
 return c
end
function A.validateRadius(radius)
 radius=tonumber(radius)
 assert(radius and radius==math.floor(radius)and radius&gt;=100 and radius&lt;=20000,'Radius must be a whole number from 100 to 20000 game units.')
 return radius
end
local function distance(r,snake,actor)
 local squared=0
 for i=0,2 do
  local delta=signed(u16(r+snake+0x20+i*2))-signed(u16(r+actor+0x20+i*2))
  squared=squared+delta*delta
 end
 return math.sqrt(squared)
end
function A.nearby(radius)
 radius=A.validateRadius(radius)
 -- Cached scans only nominate candidates. A.apply always rediscovers native
 -- evidence from current RAM and checks range again before any target write.
 local c=A.inspect(true);c.radius=radius;c.inRange=0;c.nearEligible=0
 for _,g in ipairs(c.guards)do
  g.distance=distance(c.ram,c.snake,g.actor.offset);g.inRange=g.distance&lt;=radius
  if g.inRange then c.inRange=c.inRange+1;if g.eligible then c.nearEligible=c.nearEligible+1 end end
 end
 return c
end
function A.apply(mode,options)
 assert(mode=='kill'or mode=='knockout','Choose kill or knockout.')
 options=options or {};local radius=options.radius and A.validateRadius(options.radius)or nil
 local c=A.inspect()
 if radius then
  c.eligible=0
  for _,g in ipairs(c.guards)do if g.eligible then
   g.distance=distance(c.ram,c.snake,g.actor.offset)
   if g.distance&lt;=radius then c.eligible=c.eligible+1 else g.eligible=false;g.reason='outside proximity radius'end
  end end
 end
 assert(c.eligible&gt;0,'No eligible standard guards. '..(c.reason or 'Already down, busy, outside radius, or unsupported.'))
 local writes,notifications={},{}
 local function plan(a,v,label)
  writes[#writes+1]={address=a,before=u16(a),value=v,label=label}
 end
 for _,g in ipairs(c.guards)do if g.eligible then
  local t=g.target
  plan(t+0x3E,mode=='kill'and 1 or 3,'damage mode')
  if mode=='kill'then plan(t+0x26,0,'vital')else plan(t+0x2A,0,'faint')end
  plan(t+0x28,mode=='kill'and g.hp or 0,'damage amount')
  for _,o in ipairs({0x2C,0x2E,0x30})do plan(t+o,0,'impact force')end
  notifications[#notifications+1]={address=t+6,before=g.flags,value=g.flags|4,label='damage notification'}
 end end
 -- Validate the whole batch before any writes; never reuse a previous area.
 local fresh=context();assert(fresh.ram==c.ram and fresh.stage==c.stage and fresh.snake==c.snake,'Area/player changed; refresh.')
 assert(bytes(c.ram+c.damage.fn,#c.damage.code)==c.damage.code and bytes(c.ram+c.damage.tableOffset,36)==c.damage.switch,'Guard damage code changed.')
 assert(bytes(c.profileProof.address,32)==c.profileProof.bytes,'Guard commander binding changed.')
 for _,e in ipairs(c.ownership)do for _,p in ipairs(e.blocks)do assert(bytes(p.address,#p.bytes)==p.bytes,'Guard native ownership code changed.')end end
 for _,g in ipairs(c.guards)do if g.eligible then
  local a,t=g.actor,g.target;local w=c.ram+a.offset
  assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+20)==a.namePointer and readString(c.ram+(a.namePointer&amp;0x1FFFFF),48)=='watcher.c','Guard actor changed.')
  assert(u32(c.ram+c.profile.command+0xC8+a.slot*0x10+0xC)==0x80000000+a.offset and readBytes(w+0xB78,1)==a.slot,'Commander no longer owns guard.')
  assert(u32(w+0x900)==g.pointer and u32(w+0x8EC)==g.action,'Guard target/action changed; retry.')
  assert(u16(t)==g.class and u16(t+2)==2 and u16(t+0x26)==g.hp and u16(t+0x2A)==g.faint and u16(t+0x42)==0 and u16(w+0xC2C)==0,'Guard damage state changed; retry.')
  if radius then assert(distance(c.ram,c.snake,a.offset)&lt;=radius,'Guard moved outside the proximity radius; retry.')end
 end end
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do assert(u16(v.address)==v.before,'Guard state changed; retry.')end end
 local count=0
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do
  assert(writeSmallInteger(v.address,v.value),'Guard write failed after '..count..' writes.');count=count+1
 end end
 A.last={mode=mode,pid=A.pid,ram=c.ram,stage=c.stage,affected=c.eligible,skipped=c.total-c.eligible,writes=count,guards=c.guards,recovery=c.recovery,command=c.profile.command,radius=radius}
 A.status=string.format('%s requested for %d guards; %d skipped. Resume gameplay.',mode,c.eligible,c.total-c.eligible)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../logs/guard-state-actions.csv','a+'))
  local success,problem=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Guard action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,action,guard,target,hp_before,faint_before\n'))end
   for _,g in ipairs(c.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%08X,%08X,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),A.pid,c.stage,mode,0x80000000+g.actor.offset,g.pointer,g.hp,g.faint)))end end
  end)
  f:close();assert(success,problem)
 end)
 if not ok then A.logError=tostring(err)end
 MGSGuardState=A;return A.last
end
function A.extendKnockout(result,ticks)
 assert(result==A.last and result.mode=='knockout','A fresh knockout result is required.')
 assert(type(ticks)=='number'and ticks==math.floor(ticks)and ticks&gt;=30 and ticks&lt;=10000,'Invalid recovery delay.')
 if A.extension then A.extension.stop()end
 local T={extended=0,stopped=false,remaining={},writes={}};A.extension=T
 for _,g in ipairs(result.guards)do if g.eligible then T.remaining[#T.remaining+1]=g end end
 local start=getTickCount();local timer=createTimer(nil,false);timer.Interval=100;T.timer=timer
 function T.stop()if not T.stopped then T.stopped=true;timer.Enabled=false;timer.destroy()end end
 function T.tick()
  if T.stopped then return end
  local ok,err=pcall(function()
   local c=context();assert(c.ram==result.ram and c.stage==result.stage,'Area changed; recovery extension cancelled.')
   local r=c.ram;assert(bytes(r+result.recovery.fn,#result.recovery.code)==result.recovery.code,'Recovery code changed.')
   for i=#T.remaining,1,-1 do
    local g=T.remaining[i];local a=g.actor;local w=r+a.offset
    assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+0x900)==g.pointer,'Guard owner changed.')
    assert(u32(r+result.command+0xC8+a.slot*0x10+0xC)==0x80000000+a.offset and readBytes(w+0xB78,1)==a.slot,'Guard commander changed.')
    assert(u16(g.target+2)==2 and u16(g.target+0x26)==g.hp,'Guard health/side changed.')
    local time=u32(w+0x8F4)
    if u32(w+0x8EC)==0x80000000+result.recovery.fn and time&gt;=1 and time&lt;32767-ticks and u16(g.target+0x2A)==0 and u16(g.target+0x42)==0 and u32(w+0xB70)&amp;0x20~=0 then
     local old=u16(w+0xB5A);assert(old&lt;32768,'Recovery threshold differs.')
     local value=math.max(old,time+ticks)
     assert(writeSmallInteger(w+0xB5A,value),'Recovery delay write failed.')
     T.writes[#T.writes+1]={actor=a.offset,before=old,after=value};T.extended=T.extended+1;table.remove(T.remaining,i)
    end
   end
   if #T.remaining==0 then A.status='Extended knockout applied to '..T.extended..' guards; they will recover normally.';T.stop()end
  end)
  if not ok then T.error=tostring(err);A.status='Recovery extension stopped: '..T.error;T.stop()
  elseif getTickCount()-start&gt;=15000 then T.error='Timed out waiting for guards to reach the floor.';A.status=T.error;T.stop()end
 end
 timer.OnTimer=T.tick;timer.Enabled=true
 A.status='Knockout requested; waiting to extend the normal recovery timers.'
 return T
end
MGSGuardState=A
return A
]====]):sub(2),
 [ [====[mgs-inventory.lua]====] ]=([====[!-- One-shot inventory grants and normal game equipment-selection requests.
-- All weapon/item slots are selectable, including equipment not yet owned.
if MGSInventory and MGSInventory.pid==getOpenedProcessID()then return MGSInventory end
if MGSInventory and MGSInventory.closeLog then MGSInventory.closeLog()end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local G={pid=R.pid,reader=R,version=1,pending={},status='Choose equipment to add to inventory.'}
G.weapons={
 {id=0,name='SOCOM',stock=25},{id=1,name='FAMAS',stock=100},
 {id=2,name='Grenade',stock=8},{id=3,name='Nikita',stock=10},
 {id=4,name='Stinger',stock=10},{id=5,name='Claymore',stock=8},
 {id=6,name='C4',stock=8},{id=7,name='Stun grenade',stock=8},
 {id=8,name='Chaff grenade',stock=8},{id=9,name='PSG1',stock=10},
}
G.gadgets={
 {id=0,name='Cigarettes'},{id=1,name='Binoculars'},
 {id=2,name='Cardboard box A'},{id=3,name='Cardboard box B'},{id=4,name='Cardboard box C'},
 {id=5,name='Night-vision goggles'},{id=6,name='Thermal goggles'},
 {id=7,name='Gas mask'},{id=8,name='Body armor'},{id=9,name='Ketchup'},
 {id=10,name='Stealth camouflage'},{id=11,name='Bandana'},{id=12,name='Camera'},
 {id=13,name='Rations',kind='consumable',stock=5},
 {id=14,name='Cold medicine',kind='consumable',stock=5},
 {id=15,name='Diazepam',kind='consumable',stock=5},
 {id=16,name='PAL key',note='Adds the PAL key. Its temperature/state stays under game control.'},
 {id=17,name='Key card',kind='level',stock=7,note='Choose an access level from 1 to 7.'},
 {id=18,name='Time bomb (story countdown)',kind='timer',stock=30000,equipable=false,
  note='Story time-bomb value. Adding it can start a countdown; the value uses game timer units.'},
 {id=19,name='Mine detector'},{id=20,name='MO disk'},{id=21,name='Rope'},
 {id=22,name='Handkerchief'},
 {id=23,name='SOCOM suppressor',equipable=false,note='Adds the suppressor. SOCOM attaches it through the normal weapon update.'},
}
local function u16(a)return assert(readSmallInteger(a),'Inventory read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Game state unavailable')&amp;0xFFFFFFFF end
local function signed32(v)return v&gt;=0x80000000 and v-0x100000000 or v end
local function owned(raw)return raw~=0xFFFF end
local function amount(raw)return owned(raw)and (raw&amp;0x7FFF)or 0 end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xFFFF),'Inventory write failed')end
local function fingerprint(a,expected)
 local b=assert(readBytes(a,#expected,true),'Equipment-switch code unavailable')
 for i,v in ipairs(expected)do assert(b[i]==v,'Equipment-switch layout differs')end
end
local function entry(kind,id)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Select valid equipment')
 local list=kind=='weapon'and G.weapons or G.gadgets
 local e=list[id+1];assert(e and e.id==id,'Equipment ID out of range')
 return e
end
function G.context(writing)
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xADB40)==0 and u32(ram+0xAE1B0)~=0,'Wait for area loading to finish.')
 local control=u32(ram+0xAE16C)
 assert(control&gt;=0x80000020 and control&lt;0x80200000,'Snake is not ready.')
 local work=(control&amp;0x1FFFFF)-0x20
 assert(work+0xA24&lt;0x200000,'Snake actor bounds differ.')
 assert(u32(ram+work+8)==0x8005CE1C and u32(ram+work+12)==0x8005D514,'Wait for normal gameplay.')
 assert(u32(ram+0xAE198)==0x80000000+work+0x9C,'Snake body ownership differs.')
 local flags=u32(ram+0xADB3C);local player=u32(ram+0xAE1C8)
 local ready=h.health&gt;0 and u32(ram+0xADB44)==0 and flags&amp;0xD40C0000==0 and player&amp;0x20002084==0
 if writing then assert(ready,'Finish the cutscene or restricted action first.')end
 return {h=h,ram=ram,work=work,ready=ready,frame=u32(ram+0xAE160),
  activeWeapon=signed32(u32(ram+work+0x918)),activeGadget=signed32(u32(ram+work+0x9A4)),
  stage=readString(ram+0xB7500,16)or '?'}
end
local function log(kind,e,requested,actual,equipping,c)
 local ok,err=pcall(function()
  if not G.log then
   G.logPath=dir..'../logs/inventory-actions-'..G.pid..'.csv'
   G.log=assert(io.open(G.logPath,'a'))
   if G.log:seek()==0 then G.log:write('utc,stage,category,id,name,requested,actual,equip\n')end
  end
  local name='"'..e.name:gsub('"','""')..'"'
  assert(G.log:write(table.concat({os.date('!%Y-%m-%dT%H:%M:%SZ'),c.stage,kind,e.id,name,requested,actual,equipping and 1 or 0},',')..'\n'))
  G.log:flush()
 end)
 if not ok then G.logError=tostring(err)end
end
function G.closeLog()
 if G.log then G.log:close();G.log=nil end
end
function G.equip(kind,id,c)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Equipment ID must be an integer')
 local e=id==-1 and {id=-1,name='Nothing'}or entry(kind,id)
 assert(e.equipable~=false,'Add this item to inventory; it is not directly equipped.')
 c=c or G.context(true)
 local address=kind=='weapon'and 0xB7532 or 0xB755A
 if id&gt;=0 then assert(owned(u16(c.ram+address+id*2)),'Add the selected equipment first.')end
 -- These are the same requested slots used by the normal inventory menu.
 -- The game creates/removes equipment actors and updates its active caches.
 local slot=kind=='weapon'and 0xB752C or 0xB752E
 put16(c.ram+slot,id)
 G.pending[kind]={id=id,name=e.name,ram=c.ram,work=c.work,frame=c.frame}
 G.status=e.name..' selected. Resume gameplay to finish equipping.'
 return true
end
function G.grant(kind,id,quantity,equipping)
 local e=entry(kind,id)
 assert(not equipping or e.equipable~=false,'This item is added to inventory without equipping.')
 quantity=tonumber(quantity or e.stock or 1)
 local maximum=kind=='weapon'and 9999 or e.kind=='level'and 7 or e.kind=='timer'and 32767 or e.kind=='consumable'and 9999 or 1
 assert(quantity and quantity==math.floor(quantity)and quantity&gt;=1 and quantity&lt;=maximum,'Amount must be a whole number from 1 to '..maximum..'.')
 local c=G.context(true)
 fingerprint(c.ram+0x53B2C,{0x0B,0x80,0x02,0x3C,0x2C,0x75,0x42,0x84,0x05,0,0x60,0x12,0x18,0x09,0x02,0xAE})
 fingerprint(c.ram+0x53EEC,{0x0B,0x80,0x02,0x3C,0x2E,0x75,0x42,0x84,0x05,0,0x80,0x12,0xA4,0x09,0x22,0xAE})
 local base=kind=='weapon'and 0xB7532 or 0xB755A
 local address=c.ram+base+id*2;local raw=u16(address)
 local value=(kind=='weapon'or e.kind)and math.max(amount(raw),quantity)or 1
 assert(value&lt;32768,'Existing inventory count is invalid.')
 local capacity
 if kind=='weapon'then capacity=c.ram+0xB7546+id*2
 elseif e.kind=='consumable'then capacity=c.ram+0xB755A+(id+11)*2 end
 if capacity then
  local old=u16(capacity);if old&gt;=32768 then old=0 end
  if old&lt;value then put16(capacity,value)end
 end
 put16(address,value)
 local actual=u16(address)
 assert(owned(actual),'Game did not retain the inventory entry.')
 G.status=e.name..' added to inventory.'
 if equipping then G.equip(kind,id,c)end
 log(kind,e,quantity,actual,equipping,c)
 return {id=id,name=e.name,value=actual,capacity=capacity and u16(capacity)or nil,equipping=not not equipping}
end
function G.inspect()
 local c=G.context(false);c.inventory={}
 for _,e in ipairs(G.gadgets)do c.inventory[e.id]=u16(c.ram+0xB755A+e.id*2)end
 for kind,p in pairs(G.pending)do
  local actual=kind=='weapon'and c.activeWeapon or c.activeGadget
  local requested=kind=='weapon'and c.h.weapon or c.h.item
  if actual==p.id then
   G.status=p.name..' equipped.';G.pending[kind]=nil
  elseif c.ram~=p.ram or c.work~=p.work then
   G.status=p.name..' was added; the area changed before equipment was confirmed.';G.pending[kind]=nil
  elseif c.frame-p.frame&gt;180 and requested~=p.id then
   G.status=p.name..' is in inventory. The game selected different equipment.';G.pending[kind]=nil
  end
 end
 return c
end
G.entry=entry;G.owned=owned;G.amount=amount
MGSInventory=G
return G
]====]):sub(2),
 [ [====[mgs-no-alert.lua]====] ]=([====[!-- Data-only guard/camera suppression. Profiles are resolved from live MIPS code.
if MGSNoAlert then
 assert(MGSNoAlert.version==2 and MGSNoAlert.pid==getOpenedProcessID(),'Stop the previous no-alert controller before upgrading')
 return MGSNoAlert
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local D=dofile(dir..'mgs-discovery.lua')
local A={pid=R.pid,reader=R,discovery=D,version=2,enabled=false,wanted=false,status='OFF',rebinds=0,cache={}}
local MASK=0x17
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
local function u16(a)return assert(readSmallInteger(a),'Short read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Word read unavailable')&amp;0xFFFFFFFF end
local function byte(a)return assert(readBytes(a,1),'Byte read unavailable')end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xFFFF),'Short write failed')end
local function put32(a,v)assert(writeInteger(a,v&amp;0xFFFFFFFF),'Word write failed')end
local function put8(a,v)assert(writeBytes(a,v&amp;255),'Byte write failed')end
local function stamp(ram,p,n)
 local b=assert(readBytes(ram+p,n or 16,true),'Code fingerprint unavailable')
 return string.char(table.unpack(b))
end
local function family(a)return a.name..':'..a.act..':'..a.die end
local function actorSame(a,b)return a and b and a.offset==b.offset and a.act==b.act and a.die==b.die and a.name==b.name end
local function now()return getTickCount and getTickCount()or math.floor(os.clock()*1000)end
function A.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xADB40)==0 and u32(ram+0xAE1B0)~=0,'Area loading')
 local stage=assert(readString(ram+0xB7500,16),'Stage unavailable')
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Stage not ready')
 local actors=D.actors(ram);local present={};local families={};local samples={}
 for _,a in ipairs(actors)do
  present[a.offset]=a
  if a.name=='watcher.c'or cameraNames[a.name]or a.name=='command.c'then
   local key=family(a)
   if not families[key]then families[key]=true;samples[#samples+1]=key..stamp(ram,a.act&amp;0x1FFFFF,32)end
  end
 end
 table.sort(samples)
 local epoch=tostring(ram)..':'..stage
 local key=epoch..':'..table.concat(samples,'|')
 local profile=A.cache[key]
 if profile then
  if profile.guard and stamp(ram,profile.guard.proofPC,32)~=profile.guard.proof then profile=nil end
  if profile then for _,p in pairs(profile.cameras)do if stamp(ram,p.loadPC,16)~=p.proof then profile=nil;break end end end
 end
 if not profile or (profile.unsupported&gt;0 and now()-(profile.time or 0)&gt;1000)then
  local code=D.overlay(ram)
  profile={cameras={},unsupported=0,time=now()}
  local p,why=D.guardProfile(ram,actors,code);profile.guard=p;profile.guardReason=why
  local checked={}
  for _,a in ipairs(actors)do
   if a.name=='watcher.c'and not p then profile.unsupported=profile.unsupported+1 end
   if cameraNames[a.name]and not checked[family(a)]then
    checked[family(a)]=true
    local cp,err=D.cameraProfile(a,code)
    if cp then cp.proof=stamp(ram,cp.loadPC,16);profile.cameras[family(a)]=cp
    else profile.unsupported=profile.unsupported+1;profile.cameraReason=err end
   end
  end
  if p then p.proofPC=p.visionPC-12;p.proof=stamp(ram,p.proofPC,32)end
  A.cache[key]=profile
 end
 local c={ram=ram,stage=stage,epoch=epoch,key=key,h=h,actors=present,profile=profile,guards=D.guardActors(ram,actors,profile.guard),cameras={}}
 for _,a in ipairs(actors)do
  local cp=profile.cameras[family(a)]
  if cp then a.cameraProfile=cp;c.cameras[a.offset]=a end
 end
 return c
end
local function fresh(c)
 -- Stage/DRAM changes unload the previous area. Never restore through its old
 -- addresses into a replacement overlay or replacement actor allocation.
 if not A.snapshot or A.snapshot.epoch~=c.epoch then
  A.snapshot={epoch=c.epoch,ram=c.ram,stage=c.stage,guards={},cameras={}}
  A.rebinds=A.rebinds+1
 end
 local s=A.snapshot;local p=c.profile.guard
 if p then
  if not s.guard or s.guard.profile.command~=p.command or s.guard.profile.proof~=p.proof then
   s.guard={profile=p,ranges={}}
  end
  for i=0,2 do
   local v=u16(c.ram+p.ranges+i*2)
   if v~=0x8000 then assert(v&lt;32768,'Existing negative guard range');s.guard.ranges[i+1]=v end
   assert(s.guard.ranges[i+1]~=nil,'Guard ranges already modified without ownership')
  end
 end
 return s
end
local function apply(c)
 local s=fresh(c);local ng,nc=0,0
 if c.profile.guard then
  local p=c.profile.guard
  for i=0,2 do if u16(c.ram+p.ranges+i*2)~=0x8000 then put16(c.ram+p.ranges+i*2,0x8000)end end
  if u32(c.ram+p.eye)~=0xFFFF8000 then put32(c.ram+p.eye,0xFFFF8000)end
  for o,g in pairs(c.guards)do
   ng=ng+1;local flags=byte(c.ram+o+0xBA3);local saved=s.guards[o]
   if not saved or not actorSame(saved.actor,g)or saved.actor.slot~=g.slot then saved={actor=g,mask=flags&amp;MASK};s.guards[o]=saved end
   saved.mask=saved.mask|(flags&amp;MASK)
   if flags&amp;MASK~=0 then put8(c.ram+o+0xBA3,flags&amp;(~MASK&amp;255))end
   for _,field in ipairs({0xB92,0xB94})do if u16(c.ram+o+field)~=0 then put16(c.ram+o+field,0)end end
   if u32(c.ram+o+0xB98)~=0 then put32(c.ram+o+0xB98,0)end
   for _,field in ipairs({0xBA1,0xBA2})do if byte(c.ram+o+field)~=0 then put8(c.ram+o+field,0)end end
  end
 end
 for o,camera in pairs(c.cameras)do
  nc=nc+1;local cp=camera.cameraProfile
  local v=cp.size==4 and u32(c.ram+o+cp.range)or u16(c.ram+o+cp.range);local old=s.cameras[o]
  if not old or not actorSame(old.actor,camera)or old.field~=cp.range or old.size~=cp.size or old.proof~=cp.proof then
   old={actor=camera,field=cp.range,size=cp.size,range=v,proof=cp.proof,pc=cp.loadPC};s.cameras[o]=old
  elseif v~=0 then old.range=v end -- reinitialized/replaced camera parameters
  if v~=0 then if cp.size==4 then put32(c.ram+o+cp.range,0)else put16(c.ram+o+cp.range,0)end end
 end
 A.guardCount=ng;A.cameraCount=nc;A.stage=c.stage;A.profile=c.profile
 A.status=string.format('ON | %s | %d guards, %d cameras | area binds %d',c.stage,ng,nc,A.rebinds)
 if c.profile.unsupported&gt;0 then A.status=A.status..' | PARTIAL: unrecognized sensing layout'end
end
local function restore()
 if not A.snapshot then return end
 assert(getOpenedProcessID()==A.pid,'Original process required for cleanup')
 local c=A.context();local s=A.snapshot
 if c.epoch~=s.epoch then A.snapshot=nil;return end
 local p=s.guard and s.guard.profile
 if p and stamp(c.ram,p.proofPC,32)==p.proof then
  for i,v in ipairs(s.guard.ranges)do put16(c.ram+p.ranges+(i-1)*2,v)end
  local mode=u32(c.ram+p.command+0x18)
  if mode&lt;=2 then local r=s.guard.ranges[mode+1];put32(c.ram+p.eye,r);put32(c.ram+p.shoot,r+500)end
 end
 for o,old in pairs(s.guards)do
  local g=c.actors[o]
  if actorSame(g,old.actor)and byte(c.ram+o+0xB78)==old.actor.slot then
   put8(c.ram+o+0xBA3,(byte(c.ram+o+0xBA3)&amp;(~MASK&amp;255))|old.mask)
  end
 end
 for o,old in pairs(s.cameras)do
  if actorSame(c.actors[o],old.actor)and stamp(c.ram,old.pc,16)==old.proof then
   if old.size==4 then put32(c.ram+o+old.field,old.range)else put16(c.ram+o+old.field,old.range)end
  end
 end
 A.snapshot=nil
end
function A.disable()
 A.wanted=false;A.enabled=false
 local ok,err=pcall(restore)
 if not ok then A.status='CLEANUP WAITING: '..tostring(err);return false,A.status end
 A.status='OFF';return true
end
function A.enable()
 assert(not A.stopped,'Reload the stopped no-alert controller')
 if A.wanted then return true end
 assert(not A.snapshot,'Finish pending cleanup before enabling')
 local c=A.context()
 A.wanted=true;A.enabled=true
 local ok,err=pcall(apply,c)
 if not ok then A.disable();error(err)end
 return true
end
function A.tick()
 if A.stopped then return end
 if not A.wanted then if A.snapshot then A.disable()end;return end
 if getOpenedProcessID()~=A.pid then A.enabled=false;A.status='WAITING: original process required';return end
 local ok,err=pcall(function()apply(A.context())end)
 if ok then A.enabled=true else A.enabled=false;A.status='WAITING FOR AREA: '..tostring(err)end
end
function A.stop()
 local ok,err=A.disable();if not ok then return false,err end
 A.stopped=true;A.timer.Enabled=false;A.timer.destroy();A.timer=nil
 if MGSNoAlert==A then MGSNoAlert=nil end
 return true
end
A.timer=createTimer(nil,false);A.timer.Interval=50;A.timer.OnTimer=A.tick;A.timer.Enabled=true
MGSNoAlert=A
return A
]====]):sub(2),
 [ [====[mgs-oxygen.lua]====] ]=([====[!-- US MGS shared oxygen refill: one halfword, no health/code/story writes.
if MGSOxygen and MGSOxygen.pid==getOpenedProcessID()and not MGSOxygen.stopped then return MGSOxygen end
if MGSOxygen and MGSOxygen.timer then MGSOxygen.timer.Enabled=false;MGSOxygen.timer.destroy()end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local O={pid=R.pid,version=1,requested=false,enabled=false,status='OFF',refills=0,stopped=false}
local function u32(a)return assert(readInteger(a),'Oxygen state unavailable')&amp;0xFFFFFFFF end
local function u16(a)return assert(readSmallInteger(a),'Oxygen unavailable')&amp;0xFFFF end
local function proof(a,hex)
 local expected=hex:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)
 local actual=assert(readBytes(a,#expected,true),'Oxygen HUD code unavailable')
 assert(#actual==#expected,'Incomplete oxygen code read')
 for i=1,#expected do assert(actual[i]==expected:byte(i),'US oxygen code differs')end
end
function O.context()
 assert(getOpenedProcessID()==O.pid,'Attached process changed')
 local h=R.read();local r=h.ram
 assert(h.health&gt;0 and u32(r+0xADB44)==0,'Enter living gameplay')
 assert(u32(r+0xADB40)==0 and u32(r+0xAE1B0)~=0,'Wait for area loading')
 assert(u32(r+0xAE0A0)==0,'Resume gameplay')
 assert(u32(r+0xADB3C)&amp;0xD40C0000==0 and u32(r+0xAE1C8)&amp;0x20002084==0,'Finish scene or restricted action')
 assert(u32(r+0xBFAD0)==0x8003A948 and u32(r+0xBFAD4)==0x8003AA94 and u16(r+0xBFAF2)==0,'Close the menu')
 local p=u32(r+0xAE16C)
 assert(p&gt;=0x80010020 and p+0x100&lt;0x80200000,'Invalid Snake owner')
 local w=(p&amp;0x1FFFFF)-0x20
 assert(u32(r+w+8)==0x8005CE1C and u32(r+w+12)==0x8005D514,'Normal US Snake required')
 assert(u32(r+0xAE198)==0x80000000+w+0x9C,'Snake body owner differs')
 -- Resident HUD consumes GM_O2 at AE1AC and compares it against1024.
 proof(r+0x41834,'0B80073CACE1E784000402241400A2AF0A80023C500D42241800A2AF0C00C6246B04010C1000A7AF')
 proof(r+0x419C0,'0B80023CACE142842A00239200044228040040102128000201000424')
 local oxygen=u16(r+0xAE1AC);assert(oxygen&lt;=1024,'Oxygen layout outside native range')
 return {ram=r,work=w,oxygen=oxygen}
end
function O.refill()
 local c=O.context();local fresh=O.context()
 assert(c.ram==fresh.ram and c.work==fresh.work,'Oxygen owner changed')
 if fresh.oxygen&lt;1024 then
  assert(writeSmallInteger(fresh.ram+0xAE1AC,1024),'Oxygen refill failed')
  assert(u16(fresh.ram+0xAE1AC)==1024,'Oxygen verification failed')
  O.refills=O.refills+1
 end
 O.enabled=true;O.status='ON - infinite O2';O.ram=fresh.ram
end
function O.tick()
 if O.stopped or not O.requested then return end
 local ok,err=pcall(O.refill)
 if not ok then O.enabled=false;O.status='WAITING: '..tostring(err)end
end
function O.enable()assert(not O.stopped,'Reload oxygen controller');O.requested=true;O.tick();return true end
function O.disable()O.requested=false;O.enabled=false;O.status='OFF';return true end
function O.stop()
 O.disable();O.stopped=true;O.timer.Enabled=false;O.timer.destroy();O.timer=nil
 if MGSOxygen==O then MGSOxygen=nil end
end
O.timer=createTimer(nil,false);O.timer.Interval=50;O.timer.OnTimer=O.tick;O.timer.Enabled=true
MGSOxygen=O
return O
]====]):sub(2),
 [ [====[mgs-reader.lua]====] ]=([====[!-- Read-only reader for the recorded Master Collection executable / US base game.
-- Field meanings cross-checked against FoxdieTeam/mgs_reversing linkvar.h,
-- then the current game's MIPS code. No game calls, hooks, allocations or writes.
assert(process=='METAL GEAR SOLID.exe','Attach to METAL GEAR SOLID.exe')
assert(getModuleSize(process)==30007296,'Unsupported executable image size')
local base=getAddress(process)
local pid=getOpenedProcessID()
local R={pid=pid,module=base,vtable=base+0xAB8CF0,version=1}
local function bytes(address,n)
 local b=readBytes(address,n,true)
 assert(b and #b==n,'Memory unavailable at '..string.format('%X',address))
 return b
end
local function fingerprint(address,expected)
 local actual=bytes(address,#expected)
 for i,v in ipairs(expected)do assert(actual[i]==v,'Unsupported code/layout at '..string.format('%X',address))end
end
fingerprint(base+0x10B43D,{0x48,0x8D,0x05,0xAC,0xD8,0x9A,0x00})
fingerprint(base+0x10B447,{0x41,0xB9,0x00,0x40,0x08,0x00})
local function validateRAM(ram)
 assert(ram and ram&gt;0x10000,'Emulated RAM missing')
 assert(readString(ram+0x10000,11)=='SLUS_007.76' and readString(ram+0x1000C,11)=='SLUS_005.94',
  'Only the observed US base-game layout is supported; region/variant differs')
 fingerprint(ram+0x3E644,{0x0B,0x80,0x03,0x3C,0x26,0x75,0x63,0x84,0x0B,0x80,0x02,0x3C,0x28,0x75,0x42,0x84})
 fingerprint(ram+0x30330,{0x0B,0x80,0x04,0x3C,0x78,0xE1,0x84,0x8C})
 fingerprint(ram+0x30418,{0x0B,0x80,0x03,0x3C,0x90,0xE1,0x63,0x8C})
end
local pattern={}
for i=0,7 do pattern[#pattern+1]=string.format('%02X',(R.vtable&gt;&gt;(8*i))&amp;255)end
local found=AOBScan(table.concat(pattern,' '),'+W-C',fsmAligned,'8')
local candidates={}
if found then
 for i=0,found.Count-1 do
  local owner=tonumber(found[i],16)
  local ram=readQword(owner+0x28)
  if pcall(validateRAM,ram)then candidates[#candidates+1]={owner=owner,ram=ram}end
 end
 found.destroy()
end
assert(#candidates==1,'Expected one validated emulator RAM owner; found '..#candidates)
R.owner=candidates[1].owner;R.ram=candidates[1].ram
local function u16(b,o)return b[o+1]|(b[o+2]&lt;&lt;8)end
local function s16(b,o)local n=u16(b,o);return n&gt;=32768 and n-65536 or n end
local function u32(b,o)return u16(b,o)|(u16(b,o+2)&lt;&lt;16)end
R.weapons={'SOCOM','FAMAS','Grenade','Nikita','Stinger','Claymore','C4','Stun grenade','Chaff grenade','PSG1'}
R.modes={[0]='NORMAL',[1]='JAMMING',[2]='EVASION',[3]='ALERT',[4]='SCRIPTED',[10]='TORTURE'}
function R.read()
 assert(getOpenedProcessID()==pid and process=='METAL GEAR SOLID.exe','Attached process changed; reload this project reader')
 assert(readQword(R.owner)==R.vtable,'Emulator owner unavailable; reload after returning to gameplay')
 local ram=readQword(R.owner+0x28)
 -- A game switch can replace the guest inside the same RAM allocation.
 validateRAM(ram);R.ram=ram
 local q=bytes(ram+0xB7510,192)
 local globals=bytes(ram+0xAE160,0x50)
 local h={pid=pid,ram=ram,health=s16(q,0x16),maximum=s16(q,0x18),weapon=s16(q,0x1C),item=s16(q,0x1E),
  magazine=s16(globals,4),magazineMax=s16(globals,0x44),alertMode=u32(globals,0x18),alertLevel=u32(globals,0x30),
  ammo={},ammoMax={},ration=s16(q,0x64),rationMax=s16(q,0x7A)}
 assert(h.maximum&gt;=1 and h.maximum&lt;=2000 and h.health&gt;=0 and h.health&lt;=h.maximum,'Health layout invalid or gameplay not ready')
 assert(h.weapon&gt;=-1 and h.weapon&lt;=9 and h.item&gt;=-1 and h.item&lt;=23,'Equipment layout invalid')
 assert(R.modes[h.alertMode] and h.alertLevel&lt;=65535,'Alert layout invalid')
 for i=1,10 do h.ammo[i]=s16(q,0x22+(i-1)*2);h.ammoMax[i]=s16(q,0x36+(i-1)*2)end
 h.weaponName=h.weapon==-1 and 'None' or R.weapons[h.weapon+1]
 h.ammoSelected=h.weapon&gt;=0 and h.ammo[h.weapon+1]or nil
 h.ammoSelectedMax=h.weapon&gt;=0 and h.ammoMax[h.weapon+1]or nil
 h.alertName=R.modes[h.alertMode]
 return h
end
MGSReader=R
return R
]====]):sub(2),
 [ [====[mgs-room-catalog.lua]====] ]=([====[!-- Generated by analysis/build-mgs-rooms.py.
return {
 {id=[==[s00a]==],name=[==[Loading Dock]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-5756,y=1104,z=-1298}},
 {id=[==[s01a]==],name=[==[Heliport]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-1722,y=1104,z=21437}},
 {id=[==[s02a]==],name=[==[Tank Hangar]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6000,y=1104,z=0}},
 {id=[==[s02b]==],name=[==[Tank Hangar]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=0,y=1104,z=10500}},
 {id=[==[s02c]==],name=[==[Tank Hangar (Before Contacting Meryl)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=0,y=1104,z=10500}},
 {id=[==[s02d]==],name=[==[Tank Hangar (After Contacting Meryl)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=3497,y=1104,z=7647}},
 {id=[==[s02e]==],name=[==[Tank Hangar (After Torture)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=3655,y=1049,z=8345}},
 {id=[==[s03a]==],name=[==[Holding Cell]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=1500,y=1104,z=1000}},
 {id=[==[s03ar]==],name=[==[Holding Cell (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false},
 {id=[==[s03b]==],name=[==[Medical Room]==],group=[==[Story rooms]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],tested_load=false},
 {id=[==[s03c]==],name=[==[Medical Room]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state. In the tested save, entry plays cell scenes/codec and relocates Snake into the cell. Confirmed controllable afterward; full cell escape untested.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=1500,y=1104,z=1000}},
 {id=[==[s03d]==],name=[==[Holding Cell]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s03dr]==],name=[==[Holding Cell (RED)]==],group=[==[Scenes / variants]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters. US live request stalled on a black loading screen with a frozen native frame. No placement accepted. Avoid retrying until stage availability is investigated. Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s03e]==],name=[==[Holding Cell (vs. Soldiers)]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],encounter=[==[Soldier ambush]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s03er]==],name=[==[Holding Cell (vs. Soldiers) (RED)]==],group=[==[Scenes / variants]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=2000,y=1104,z=5500}},
 {id=[==[s04a]==],name=[==[Armory]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=3655,y=1049,z=8345}},
 {id=[==[s04b]==],name=[==[Armory South (vs. Ocelot)]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],encounter=[==[Revolver Ocelot]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=49736,spawn={x=-2004,y=1104,z=10163}},
 {id=[==[s04br]==],name=[==[Armory South (vs. Ocelot) (RED)]==],group=[==[Scenes / variants]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=49736,spawn={x=-2004,y=1104,z=10163}},
 {id=[==[s04c]==],name=[==[Armory South]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=3655,y=1104,z=8345}},
 {id=[==[s05a]==],name=[==[Canyon]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],encounter=[==[Tank / Raven]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=65,spawn={x=-6617,y=104,z=-12760}},
 {id=[==[s06a]==],name=[==[Warhead Storage Building 1F]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6617,y=1104,z=-12760}},
 {id=[==[s07a]==],name=[==[Warhead Storage Building B1]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6954,y=1104,z=-12760}},
 {id=[==[s07b]==],name=[==[Commander's Room]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state. One-time guarded office correction handles the observed entrance-hall relocation; no position freeze. US office placement verified at(-670,1104,875), map7DF9. Loader v10 waits for settled normal gameplay and corrects the observed hallway relocation once after validating the office floor. Native correct entries are untouched; unexpected positions or unavailable gameplay stop without repeated writes. Earlier possession/story state was not naturally reproduced in this pass.]==],encounter=[==[Psycho Mantis]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-670,y=1104,z=875}},
 {id=[==[s07br]==],name=[==[Commander's Room (RED)]==],group=[==[Scenes / variants]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters. US request from s11b stalled on black loading screen, load17, frozen frame21769381; no retry. Reload save through game. Leave out of live batches pending availability investigation. Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=-670,y=1104,z=875}},
 {id=[==[s07c]==],name=[==[Warhead Storage Building B1]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6954,y=1104,z=-12760}},
 {id=[==[s07cr]==],name=[==[Warhead Storage Building B1 (RED)]==],group=[==[Scenes / variants]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=-6954,y=1104,z=-12760}},
 {id=[==[s08a]==],name=[==[Warhead Storage Building B2]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=750,y=1104,z=-750}},
 {id=[==[s08b]==],name=[==[Laboratory]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],encounter=[==[Cyborg Ninja]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6378,y=1049,z=55}},
 {id=[==[s08br]==],name=[==[Laboratory (RED)]==],group=[==[Scenes / variants]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6378,y=1049,z=55}},
 {id=[==[s08c]==],name=[==[Corridor]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=951,y=1104,z=-750}},
 {id=[==[s08cr]==],name=[==[Corridor (RED)]==],group=[==[Scenes / variants]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=951,y=1104,z=-750}},
 {id=[==[s09a]==],name=[==[Caves]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state. US entry can start the Meryl introduction; wait for normal control. Verified textured entrance floor after the scene.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-6000,y=1104,z=11000}},
 {id=[==[s09ar]==],name=[==[Caves (RED)]==],group=[==[Scenes / variants]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=-6000,y=1104,z=11000}},
 {id=[==[s10a]==],name=[==[Underground Passage]==],group=[==[Encounters]==],note=[==[Equip PSG1 before approaching Wolf; without it the game can force retreat. Story progress determines encounter availability. US entry can start the Wolf/Meryl sequence and relocate Snake. PSG1 was added/selected before this placement test; wait for control. Boss completion untested.]==],encounter=[==[Sniper Wolf - first fight]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-1286,y=-28896,z=21681}},
 {id=[==[s10ar]==],name=[==[Underground Passage (RED)]==],group=[==[Scenes / variants]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-1286,y=-28896,z=21681}},
 {id=[==[s11a]==],name=[==[Communication Tower A]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=43477,spawn={x=4000,y=1104,z=-5500}},
 {id=[==[s11b]==],name=[==[Communication Tower Roof]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-3827,y=1104,z=22054}},
 {id=[==[s11c]==],name=[==[Communication Tower B]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=61936,spawn={x=-4000,y=-10896,z=-5500}},
 {id=[==[s11d]==],name=[==[Communication Tower A Wall]==],group=[==[Story rooms]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],tested_load=true},
 {id=[==[s11e]==],name=[==[Communication Tower B Elevator]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state. US elevator entry can start a codec call and alert combat; wait for normal control before loading another room.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=500,y=1104,z=625}},
 {id=[==[s11g]==],name=[==[Communication Tower B Roof]==],group=[==[Story rooms]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters. US entry from s11e and matching ladder s11b loaded empty exterior without controllable Snake. Guarded returns to both verified source rooms worked. Actor availability unresolved; no placement accepted.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=-3827,y=1104,z=22054}},
 {id=[==[s11h]==],name=[==[Communication Tower B Roof (vs. Hind D)]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],encounter=[==[Hind D]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s11i]==],name=[==[Communication Tower Walkway]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=6000,y=-15396,z=0}},
 {id=[==[s12a]==],name=[==[Snowfield]==],group=[==[Encounters]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],encounter=[==[Sniper Wolf - second fight]==],tested_load=false},
 {id=[==[s12b]==],name=[==[Snowfield (After vs. Sniper Wolf)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-3682,y=2604,z=-19273}},
 {id=[==[s12c]==],name=[==[Snowfield (After vs. Sniper Wolf)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-3682,y=2604,z=-19273}},
 {id=[==[s13a]==],name=[==[Blast Furnace]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-3682,y=1104,z=-19047}},
 {id=[==[s14e]==],name=[==[Cargo Elevator]==],group=[==[Story rooms]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],tested_load=false},
 {id=[==[s15a]==],name=[==[Warehouse]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=0,y=1104,z=-2000}},
 {id=[==[s15b]==],name=[==[Warehouse North]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s15c]==],name=[==[Warehouse]==],group=[==[Encounters]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],encounter=[==[Vulcan Raven]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s16a]==],name=[==[Underground Base (1F)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-750,y=1104,z=4000}},
 {id=[==[s16b]==],name=[==[Underground Base (2F)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=-750,y=-2896,z=3119}},
 {id=[==[s16c]==],name=[==[Underground Base (3F)]==],group=[==[Story rooms]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],tested_load=false},
 {id=[==[s16d]==],name=[==[Underground Base (Control Room)]==],group=[==[Story rooms]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],tested_load=false},
 {id=[==[s17a]==],name=[==[Supply Route (vs. REX)]==],group=[==[Encounters]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],encounter=[==[Metal Gear REX]==],tested_load=false},
 {id=[==[s17ar]==],name=[==[Supply Route (vs. REX) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.]==],tested_load=false},
 {id=[==[s18a]==],name=[==[Supply Route (vs. Liquid)]==],group=[==[Encounters]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],encounter=[==[Liquid Snake - rooftop]==],tested_load=false},
 {id=[==[s18ar]==],name=[==[Supply Route (vs. Liquid) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false},
 {id=[==[s19a]==],name=[==[Escape Route (Garage)]==],group=[==[Story rooms]==],note=[==[US interior placement checked by native preset load, floor contact and visible textured ground. Movement and encounters depend on story state.]==],tested_load=true,spawn_source=[==[US MGS]==],stance=0,spawn_verified=true,map=32249,spawn={x=15500,y=-396,z=-3000}},
 {id=[==[s19ar]==],name=[==[Escape Route (Garage) (RED)]==],group=[==[Scenes / variants]==],note=[==[Uses Integral interior coordinates and native map selector; US placement needs live validation. Story progress determines actors and encounters.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false,spawn_source=[==[Integral]==],stance=0,spawn_verified=false,map=32249,spawn={x=15500,y=-396,z=-3000}},
 {id=[==[s19b]==],name=[==[Escape Route (Tunnel)]==],group=[==[Encounters]==],note=[==[Normal room load. Entry position and active actors depend on story progress; loading an arena does not reset its boss.]==],encounter=[==[Liquid Snake - escape]==],tested_load=true},
 {id=[==[s19br]==],name=[==[Escape Route (Tunnel) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false},
 {id=[==[s20a]==],name=[==[Ending Demo (SCENE 28-1)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.]==],tested_load=false},
 {id=[==[s20ar]==],name=[==[Ending Demo (SCENE 28-1) (RED)]==],group=[==[Scenes / variants]==],note=[==[Scene variant; Snake may not be controllable. Resume or reload through the game if needed.  Not listed in the captured US stage archive; loader v11 rejects it while absent from the current archive.]==],tested_load=false}
}
]====]):sub(2),
 [ [====[mgs-room-loader.lua]====] ]=([====[!-- Generated by analysis/build-mgs-rooms.py.
-- One-shot native MGS room loads. Opening the dashboard never loads a room.
local prior=MGSRoomLoader
if prior and prior.pid==getOpenedProcessID()and prior.version==11 then return prior end
if prior and prior.officeTimer then prior.officeTimer.destroy();prior.officeTimer=nil end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=dofile(dir..'mgs-reader.lua')
local residentRead=R.read
function R.read()
 local h=residentRead();h.stage=readString(h.ram+0xB7500,16)
 assert(h.stage and h.stage:match('^[%w_]+$')and #h.stage&lt;=12,'Enter MGS gameplay')
 return h
end
local G=dofile(dir..'mgs-inventory.lua')
local W={pid=R.pid,version=11,catalog=dofile(dir..'mgs-room-catalog.lua'),history={},status='Choose a destination. Loading begins only when you click Load.'}
if prior and prior.pid==W.pid then
 for _,key in ipairs({'history','pending','previous','last','status'})do W[key]=prior[key]end
end
local byID={};for _,e in ipairs(W.catalog)do assert(not byID[e.id],'Duplicate destination');byID[e.id]=e end
local function u16(a)return assert(readSmallInteger(a),'Area read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Area read unavailable')&amp;0xffffffff end
local function value(r,v)return v.size==1 and assert(readBytes(r+v.offset,1))or v.size==2 and u16(r+v.offset)or u32(r+v.offset)end
local function hash(s)local n=0;for i=1,#s do n=(((n&lt;&lt;5)|(n&gt;&gt;11))+s:byte(i))&amp;0xffff end;return n end
local function fingerprint(r)
 for _,p in ipairs(W.proofs)do
  local bytes=assert(readBytes(r+p.offset,#p.bytes,true),'Native loader unavailable')
  assert(#bytes==#p.bytes,'Incomplete native loader read')
  for i=1,#p.bytes do assert(bytes[i]==p.bytes:byte(i),'MGS native stage-loader code differs')end
 end
end
function W.destination(id)
 assert(type(id)=='string'and #id&lt;=7 and id:match('^s%d%d%lr?$'),'Select a catalog destination')
 return assert(byID[id],'Destination is not in the MGS stage catalog')
end
function W.context(recoveryID)
 assert(getOpenedProcessID()==W.pid,'Attached process changed; reopen the dashboard')
 local c
 if recoveryID then
  -- Empty idle scene, or the observed s12a pad-release lock on normal Snake.
  -- The only allowed target is the verified room this exact request left.
  local h=R.read();local r=h.ram;local last=assert(W.last,'No preceding room request')
  local target=W.destination(recoveryID)
  assert(last.state=='arrived'and last.to==h.stage and last.from==recoveryID and last.ram==r,'Recovery must return from the last confirmed load')
  assert(target.spawn_verified and target.spawn and target.map~=nil,'Return room needs a verified interior preset')
  assert(getTickCount()-last.started&gt;=5000,'Wait for the scene to settle')
  assert(h.health&gt;0 and u32(r+0xadb40)==0 and u32(r+0xae1b0)~=0 and u32(r+0xadb44)==0,'Recovery requires a loaded living state')
  local flags=u32(r+0xadb3c);local player=u32(r+0xae1c8)
  -- STATE_RADAR_OFF affects display only; other empty-scene flags refuse.
  local empty=flags&amp;(~0x400000&amp;0xffffffff)==0 and player==0 and u32(r+0xae16c)==0 and u32(r+0xae198)==0
  if empty then c={ram=r,stage=h.stage,h=h}
  else error('Recovery requires an empty idle scene')end
 else local h=R.read();c=G.context(true);assert(c.ram==h.ram and c.stage==h.stage,'Reader binding changed')end
 local r=c.ram;local current=hash(c.stage)
 assert(u32(r+0xae0a0)==0,'Resume the game or dismiss its paused demo/message before loading')
 assert(u32(r+0xbfac8+8)==0x8003a948 and u32(r+0xbfac8+12)==0x8003aa94 and u16(r+0xbfac8+0x2a)==0,'Close the codec or equipment menu')
 assert(readString(r+0xadb34,8)==c.stage and u16(r+0xae138)==current and u16(r+0xb751c)==current and u16(r+0xb7fc8)==current,'Wait for the current room transition to finish')
 return c
end
-- US FS stage directory, cross-checked with native get_stage_pos at 23FD8.
-- Read each time: the loaded archive, rather than an imported catalog, decides
-- which names can be requested. No fixed blacklist and no archive writes.
function W.stageDirectory(r)
 local h=R.read();assert(not r or r==h.ram,'RAM changed before archive check');r=h.ram
 local base,size,count,tablePointer=u32(r+0x9fc34),u32(r+0x9fc38),u32(r+0x9fc3c),u32(r+0x9fc40)
 assert(base&gt;0 and base&lt;0x200000 and count&gt;0 and count&lt;=170 and size==count*12,'Stage archive header differs')
 assert(tablePointer&gt;=0x80010000 and tablePointer+size&lt;=0x80200000,'Stage directory pointer differs')
 local entries={};local previous=0;local at=r+(tablePointer&amp;0x1fffff)
 for i=0,count-1 do
  local raw=assert(readBytes(at+i*12,8,true),'Stage name unavailable')
  assert(#raw==8,'Incomplete stage name')
  local chars={};local ended=false
  for j=1,8 do
   local b=raw[j]
   if b==0 then ended=true else
    assert(not ended and (b&gt;=48 and b&lt;=57 or b&gt;=97 and b&lt;=122 or b==95),'Invalid archive stage name')
    chars[#chars+1]=string.char(b)
   end
  end
  local name=table.concat(chars);local sector=u32(at+i*12+8)
  assert(#name&gt;0 and not entries[name]and sector&gt;previous and sector&lt;0x200000,'Stage directory entries differ')
  entries[name]=sector;previous=sector
 end
 assert(entries.init and entries.s00a and entries.s01a,'Unexpected stage archive')
 return {base=base,count=count,size=size,pointer=tablePointer,entries=entries}
end
function W.requireStage(id,r)
 local archive=W.stageDirectory(r)
 assert(archive.entries[id],id..' is not listed in the current game stage archive; load cancelled before writes')
 return archive
end

-- Embedded in the US loader: one correction per explicit s07b room request.
-- Never runs merely because the dashboard opens, or freezes a moving player.
local function signed(a)local v=u16(a);return v&gt;=32768 and v-65536 or v end
local function guest(r,p,n)
 assert(p&gt;=0x80010000 and p+n&lt;=0x80200000,'Office geometry pointer differs')
 return r+(p&amp;0x1fffff)
end
function W.stopOffice(state,reason)
 local p=W.office
 if p then p.state=state;p.reason=reason end
 if W.officeTimer then W.officeTimer.Enabled=false end
end
local function officeContext(p)
 local c=W.context();local r=c.ram
 assert(c.stage=='s07b'and r==p.ram,'Office stage or RAM changed')
 fingerprint(r)
 local control=r+c.work+0x20
 local mapPointer=u32(control+0x2c);local map=guest(r,mapPointer,24)
 assert(u16(map+4)==0x7df9 and u16(map+6)~=0,'Office map differs')
 local hzd=guest(r,u32(map+8),40);local group=guest(r,u32(hzd+4),24)
 local count=u16(group+4);assert(count&gt;0 and count&lt;=2048,'Office floor count differs')
 local floors=guest(r,u32(group+12),count*48);local proven=false
 -- The rendered office point was checked live. Require its native flat floor,
 -- allowing floor-index changes across story variants without guessing ceilings.
 for i=0,count-1 do
  local f=floors+i*48
  if u16(f+6)==3 and signed(f+4)==0 and signed(f+12)==0
   and signed(f)&lt;=-670-450 and signed(f+8)&gt;=-670+450
   and signed(f+2)&lt;=875-450 and signed(f+10)&gt;=875+450 then proven=true;break end
 end
 assert(proven,'Office ground polygon unavailable')
 local x,y,z=signed(control),signed(control+2),signed(control+4)
 local height=signed(control+0x32)
 assert(height&gt;=900 and height&lt;=1200 and math.abs(y-height)&lt;=100
  and math.abs(signed(control+0x78))&lt;=100 and readBytes(control+0x57,1)==1,'Wait for grounded standing Snake')
 return {ram=r,work=c.work,control=control,map=mapPointer,group=group-r,
  frame=c.frame,x=x,y=y,z=z}
end
function W.tickOffice()
 local p=W.office
 if not p or p.state~='waiting'and p.state~='checking' then return end
 if getOpenedProcessID()~=W.pid or W.last~=p.action then W.stopOffice('cancelled','Request or process changed');return end
 if getTickCount()-p.started&gt;45000 then W.stopOffice('unconfirmed','Office placement timed out; no retry');return end
 local ok,h=pcall(R.read)
 if not ok or h.ram~=p.ram then W.stopOffice('cancelled','Guest identity changed');return end
 if h.stage~='s07b' then
  if p.seen then W.stopOffice('cancelled','Left office')end
  return
 end
 p.seen=true
 local good,c=pcall(officeContext,p)
 if not good then p.stable=0;p.sample=nil;p.reason=tostring(c);return end
 local old=p.sample;p.sample=c
 if not old or old.work~=c.work or old.map~=c.map or old.group~=c.group then p.stable=0;return end
 if old.frame==c.frame then return end
 if math.abs(c.x-old.x)&gt;32 or math.abs(c.z-old.z)&gt;32 then p.stable=0;return end
 p.stable=p.stable+1
 if p.stable&lt;5 then return end
 local inside=math.abs(c.x+670)&lt;=512 and math.abs(c.z-875)&lt;=512
 if inside then W.stopOffice('complete',p.writes==3 and 'Office correction settled' or 'Native office spawn already correct');return end
 if p.state=='checking' then W.stopOffice('unconfirmed','Position did not settle; no retry');return end
 -- Only the observed forced entrance-hall relocation is eligible.
 if c.x &lt; -2000 or c.x &gt; 2000 or c.z &lt; 12000 or c.z &gt; 16000 then
  W.stopOffice('unconfirmed','Unexpected entry position; no correction');return
 end
 local fresh=officeContext(p)
 assert(fresh.ram==c.ram and fresh.work==c.work and fresh.map==c.map and fresh.group==c.group
  and fresh.x==c.x and fresh.y==c.y and fresh.z==c.z,'Snake changed before office correction')
 -- Mark before writing so an interrupted/partial write can never retry.
 p.state='checking';p.writes=0;p.stable=0;p.sample=nil
 for i,v in ipairs({-670,1104,875})do
  assert(writeSmallInteger(fresh.control+(i-1)*2,v&amp;0xffff),'Office position write failed')
  p.writes=p.writes+1
 end
end
function W.armOffice(action)
 W.stopOffice('cancelled','Superseded by another room load')
 if action.to~='s07b' then return end
 W.office={action=action,ram=action.ram,started=getTickCount(),state='waiting',stable=0,writes=0}
 if not W.officeTimer then
  W.officeTimer=createTimer(nil,false);W.officeTimer.Interval=100
  W.officeTimer.OnTimer=function()
   local ok,err=pcall(W.tickOffice)
   if not ok then W.stopOffice('unconfirmed',tostring(err))end
  end
 end
 W.officeTimer.Enabled=true
end

function W.plan(id,recovery)
 assert(recovery==nil or type(recovery)=='boolean','Invalid recovery mode')
 local destination=W.destination(id)
 local map=destination.map
 if map~=nil then assert(type(map)=='number'and map%1==0 and map&gt;=0 and map&lt;=0xffff,'Invalid room entry map')end
 local spawn
 if destination.spawn then
  spawn={}
  for _,axis in ipairs({'x','y','z'})do
   local n=destination.spawn[axis]
   assert(type(n)=='number'and n%1==0 and n&gt;=-32768 and n&lt;=32767,'Invalid room entry coordinate')
   spawn[axis]=n
  end
 end
 assert(not W.pending,'A room load is already pending')
 local c=W.context(recovery and id or nil);local r=c.ram;fingerprint(r)
 W.requireStage(id,r)
 local current=hash(c.stage);local target=hash(id);local writes={}
 local function add(offset,size,new)
  local v={offset=offset,size=size,value=new};v.before=value(r,v);writes[#writes+1]=v
 end
 -- GM_SetArea: shift history, publish area hash and eight-byte name.
 for i=7,1,-1 do add(0xb7fc8+i*2,2,u16(r+0xb7fc8+(i-1)*2))end
 add(0xb7fc8,2,target);add(0xae138,2,target)
 local name=id..string.rep('\0',8-#id)
 for i=1,8 do add(0xadb34+i-1,1,name:byte(i))end
 -- Ordinary LoadCmd: previous/current area, then default request last.
 -- Only a recorded destination preset supplies the native LoadCmd p: vector.
 -- A recorded m: selector chooses the native sub-map. Inventory, story flags and disk are untouched.
 add(0xb75a4,2,current);add(0xb751c,2,target)
 if map~=nil then add(0xb751e,2,map)end
 if spawn then
  add(0xb7520,2,spawn.x&amp;0xffff);add(0xb7522,2,spawn.y&amp;0xffff);add(0xb7524,2,spawn.z&amp;0xffff)
 end
 if destination.stance~=nil then
  assert(spawn and destination.stance==0,'Standing stance requires a ground preset')
  assert(u16(r+0xB7530)&lt;=3,'Unsupported native stance')
  add(0xB7530,2,0)
 end
 add(0xadb40,4,0x11)
 return {pid=W.pid,ram=r,from=c.stage,to=id,destination=destination,spawn=spawn,map=map,recovery=not not recovery,writes=writes}
end
function W.request(id,recovery)
 local p=W.plan(id,recovery);local c=W.context(recovery and id or nil)
 assert(c.ram==p.ram and c.stage==p.from,'Area changed before load; try again')
 fingerprint(c.ram)
 W.requireStage(id,c.ram)
 for _,v in ipairs(p.writes)do assert(value(c.ram,v)==v.before,'Area state changed before load; try again')end
 local final=R.read();assert(final.ram==p.ram and final.stage==p.from,'Guest changed before load')
 assert(getOpenedProcessID()==p.pid and readQword(R.owner+0x28)==p.ram,'Process or RAM owner changed before load')
 local written=0
 for _,v in ipairs(p.writes)do
  local a=c.ram+v.offset;local ok
  if v.size==1 then ok=writeBytes(a,v.value)elseif v.size==2 then ok=writeSmallInteger(a,v.value)else ok=writeInteger(a,v.value)end
  if not ok then W.status='Load failed after '..written..' writes. No automatic retry.';error(W.status)end
  written=written+1
 end
 local action={from=p.from,to=p.to,ram=p.ram,spawn=p.spawn,map=p.map,recovery=p.recovery,started=getTickCount(),state='requested',writes=written}
 W.pending=action;W.last=action;W.history[#W.history+1]=action
 W.armOffice(action)
 if #W.history&gt;20 then table.remove(W.history,1)end
 W.status='Load requested: '..p.from..' -&gt; '..p.to..'. Return to the game while it loads.'
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../logs/mgs-room-loads.csv','a+'))
  local good,why=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,pid,from,to,request\n'))end
   assert(f:write(string.format('%s,%d,%s,%s,0x11\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),W.pid,p.from,p.to)))
  end)
  f:close();assert(good,why)
 end)
 if not ok then W.logError=tostring(err)end
 return action
end
function W.poll()
 assert(getOpenedProcessID()==W.pid,'Attached process changed; reopen the dashboard')
 local h=R.read();local r=h.ram;local p=W.pending
 if p then
  if r~=p.ram then
   p.state='unconfirmed';W.pending=nil;W.status='RAM changed; load result unconfirmed. No automatic retry.'
  elseif h.stage==p.to and readString(r+0xadb34,8)==p.to and u32(r+0xadb40)==0 and u32(r+0xae1b0)~=0 then
   p.state='arrived';W.pending=nil;W.previous=p.from
   W.status='Loaded '..p.to..'. Story progress determines actors, encounters and entry position.'
  elseif getTickCount()-p.started&gt;30000 then
   p.state='unconfirmed';W.pending=nil
   W.status='Load not confirmed within 30 seconds. Return to the game and check its screen; no automatic retry.'
  end
 end
 local ok,c=pcall(W.context)
 local canRecover=false
 if not ok and not W.pending and W.last then canRecover=pcall(W.context,W.last.from)end
 return {stage=h.stage,health=h.health,maximum=h.maximum,ready=ok and not W.pending,reason=not ok and tostring(c)or W.pending and 'Room load pending'or nil,
         nativeStage=readString(r+0xadb34,8),previous=W.previous,pending=W.pending,canRecover=canRecover}
end
function W.returnPrevious()
 assert(W.previous,'No previous room recorded in this dashboard session')
 return W.request(W.previous)
end
function W.recoverPrevious()
 assert(W.last,'No preceding room request')
 return W.request(W.last.from,true)
end
W.proofs={{offset=0x2DA8C,bytes=('e0ffbd271c00bfafc386000c1800b0afac86000c212040002180400000000292000000005c004010010002245686000c720004241e00401000000000ce86000c0000000012004014000000008aaf000c212000020b80043cd0e184247d44020c21284000775a000c00000000da55000c000000009b79000c00000000b75c000c2120000221204000cbb60008212800020b80043c1c7584840b80053cd0e1a52461af000c0000000009b70008010002240b80023c1c7542940b80013ca47522a4b75c000c2120000200240200032404000b80013c1c7522a461af000c212800025686000c6d0004240500401000000000ce86000c000000000b80013c1e7522a45686000c700004240f00401000000000c386000c00000000212040008b86000c1000a5271000a2971200a3971400a4970b80013c207522a40b80013c227523a40b80013c247524a45686000c730004240700401001000224ce86000c000000000b80013c40db22ac03004010800042340b80013c40db22ac5686000c6e00042408004014211000000b80023c40db428c00000000100042340b80013c40db22ac211000001c00bf8f1800b08f2000bd270800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x2BD84,bytes=('e8ffbd271000b0af218080000b80043c34db84241400bfaf3c0790a77d44020c00000000070005240b80023cc87f42240e0044240c00432400006294feff6324ffffa524000082a4fbffa01cfeff84240b80013cc87f30a4211000021400bf8f1000b08f1800bd270800e00300000000010003240b80053cca7fa5240000a2840000000005004410000000000100632408006228f9ff40140200a5240800e003211060000b80023c34db42240800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x2C3D8,bytes=('c0ffbd273000b0af21808000010004243c00bfaf3800b2af3a3b020c3400b1af01000424d23b020c2190400006004018000000000b80033c14756324000062940db10008fffb42300b80033c14756324000062940000000000044234000062a40b80023c1475429400000000002442301200401400000000b807828f0000000003004010010004241bb100080a00052421280000a53b020c00000000d007858f000000000001a2280200401400000000ff000524b83b020c010004240b80023ca0e0428cd00780afb80780af0800423013004010000000000c80023c5817428c000000000a00401400000000958e000c000000000300032405004310f7ff03240b80023ca0e0428c4cb1000824104300abb0000c000000004eb10008000000000c80023c5817428c000000000600401400000000958e000c000000000300032407004314000000000b80023ca0e0428c00000000080042340b80013ca0e022ac0b80023ca0e0428c00000000020042301f0040148888043c6407838f0b80023c9ce0428c898884342118620018006400a291053cc5b3a534c31703001040000021200301432104002320820018008500640783afc31704001040000021180401c31a030023186200c010030023104300401102002110430000110200232082000b80013cc67523a40b80013cc87524a42000118e0000000005002012010002244200221200000000d9b2000800000000b407828f000000005c014010010003244401828fb40783af8000423003004010000000000b80013cb0da20ac0b80023c0c7a428c000000000500401000000000e555000c000000009f79000c00000000c8cb000c00000000abc8000c000000006982000c00000000aec0000c000000004401828f000000001000423003004010000000001789000c000000000180043c480c84248b39020c000000004401848f440180af2000823005004010022404003083000c21280000acb1000800000000fa83000c000000000180043c580c84248b39020c0000000037eb000c0000000028c1000c0000000008c0000c0000000001000224d9b20008200002ae2400028e00000000e800401cf7ff02244801828f0000000021004010000000006b0040180f0943321a005114ffff4224d1e7000c0000000021804000ffff02240c0002160000000039e6000c01000424040040100f094332480190af2db20008000000006954000c040004242db200080f094332d1e7000c00000000540051140f09433207e8000c000000002db200080f094332480182af2db200080f0943324401838f0000000020006010000000000b80023ca0e0428c00000000020042301a0040148000623003004010ff7f023c0b80013cb0da22ac6954000c040004240b80023ca0e0428cf7ff0324241043000b80013ca0e022aca9cb000c0000000007e8000c000000004a10043c006084344001828f03000324240003ae25104400400182afd9b20008000000000b80023ca0e0428c000000000400401400d8033cc1c0000c0000000000d8033c4001828f204063342410430012004014fdff03240b80023ca0e0428c000000002410430014004014000000009806828f000000000200429400000000000842300d004010000000006db0000c000000002ab20008000000000b80023ca0e0428c000000000200423003004010000000003eb0000c0000000087cb000c000000000f0943320f090224430062145a0002246801828f000000003f0040145a0002244c07828f00000000ffff42244c0782af3a004104000000000b80043cd87f84240b80023c68f3428c0180053c680ca524801002000a80013c2108220048fa268cc144020c218080001a70020c000000009648020c212000006273020c00000000295c020c00000000253c020c000000005965020c21200000b436020c000000004b99000c00000000dd47020c03000424d26b020c0000000010000424040005241f80063cbe70020cf0ffc634956b020c00000000d26b020c00000000dc6f020c00000000d66f020c000000000180043c780c84248b39020c21280002212000021f80053c00ffa534d26f020c2130000067b20008000000004c0782af4001828f000000000a004104000000009806828f00000000220042940000000040084230030040100000000007e8000c000000003a3b020c02000424200042304e00401000000000f267020c1800a427218000001800a3273000a42740801000000062900100632401004230258002022a106400f9ff4014000000000c80053ccc18a58c0c80063c0819c68c0c80073cd019e78c0c80023cc419428c0180043c840c84248b39020c1000a2af0180043ca00c84248b39020c21280002d2b20008000000000b80033ca0e0638c2400048e24186200ffff84240b80013ca0e023ac2600801c240004aed1e7000c00000000ffff032420004314000000000b80023ca0e0428c00000000050042301300401400000000200000ae92cb000c240000ae0cb0000c0000000081b0000c212000024401828f000000004000423016004014000000001ab0000c0000000026b0000c00000000d9b20008000000004401828f000000008000423003004010000000000b80013cb0da20ac240011ae0b80023ca0e0428c000000000300401400000000feaf000c000000003c00bf8f3800b28f3400b18f3000b08f4000bd270800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x5D8F4,bytes=('0b80023c3075429400000000220a22a600140200031402002100431421202002'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)},{offset=0x23FD8,bytes=('e0ffbd271400b1af0a80113c3cfc318e1000b0af0a80103c40fc108e1800b2af219080000e00201a1c00bfaf2120000221284002a144020c0800062406004014ffff31260800038e0a80023c34fc428c0f90000821106200f4ff201e0c001026ffff02241c00bf8f1800b28f1400b18f1000b08f2000bd270800e00300000000'):gsub('%x%x',function(h)return string.char(tonumber(h,16))end)}}
MGSRoomLoader=W
return W
]====]):sub(2),
 [ [====[mgs-stats.lua]====] ]=([====[!-- One-shot edits to confirmed PSX link-variable statistics and the real clock.
if MGSStats and MGSStats.pid==getOpenedProcessID()then return MGSStats end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local S={pid=R.pid,reader=R,version=1,status='Read-only until you press Apply.'}
S.fields={
 {key='alerts',name='Alerts / times found',index=78},
 {key='kills',name='Enemies killed',index=79},
 {key='saves',name='Saves',index=88},
 {key='continues',name='Continues',index=87},
 {key='rations',name='Rations used',index=86},
 {key='pitfalls',name='Pitfall deaths',index=80},
 {key='mice',name='Mice killed',index=81},
 {key='crows',name='Crows killed',index=82},
}
local levels={[-1]='Very easy',[0]='Easy',[1]='Normal',[2]='Hard',[3]='Extreme'}
local function u16(a)return assert(readSmallInteger(a),'Statistic unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Game state unavailable')&amp;0xFFFFFFFF end
local function integer(v,minimum,maximum,name)
 v=tonumber(v)
 assert(v and v==math.floor(v)and v&gt;=minimum and v&lt;=maximum,(name or 'Value')..' must be a whole number from '..minimum..' to '..maximum..'.')
 return v
end
local function fp(ram,offset,expected)
 local b=assert(readBytes(ram+offset,#expected,true),'Statistics code unavailable')
 for i,v in ipairs(expected)do assert(b[i]==v,'Statistics code/layout differs.')end
end
function S.context(writing)
 local h=R.read();local r=h.ram
 assert(u32(r+0xADB40)==0 and u32(r+0xAE1B0)~=0,'Wait for area loading to finish.')
 local control=u32(r+0xAE16C)
 assert(control&gt;=0x80000020 and control&lt;0x80200000,'Wait for normal gameplay.')
 local work=(control&amp;0x1FFFFF)-0x20
 assert(work+0xA24&lt;0x200000 and u32(r+work+8)==0x8005CE1C and u32(r+work+12)==0x8005D514,'Snake actor differs.')
 assert(u32(r+0xAE198)==0x80000000+work+0x9C,'Snake body ownership differs.')
 local ready=h.health&gt;0 and u32(r+0xADB44)==0 and u32(r+0xADB3C)&amp;0xD40C0000==0 and u32(r+0xAE1C8)&amp;0x20002084==0
 if writing then
  assert(ready,'Finish the cutscene or restricted action first.')
  -- Resident save serialization copies these same play-time and save fields.
  fp(r,0x21CB8,{0x0B,0x80,0x03,0x3C,0xC6,0x75,0x63,0x94,0x0B,0x80,0x06,0x3C,0xC8,0x75,0xC6,0x94,0x0B,0x80,0x02,0x3C,0xC0,0x75,0x42,0x94})
  -- s1 = saved linkvar[88] at B6CF0; copy source s1-B0 = B6C40.
  fp(r,0x21CD0,{0x0B,0x80,0x11,0x3C,0xF0,0x6C,0x31,0x26})
  fp(r,0x21D18,{0x50,0xFF,0x26,0x26})
  -- Main game clock stores the derived hours and seconds here.
  fp(r,0x2C5B8,{0x0B,0x80,0x01,0x3C,0xC6,0x75,0x23,0xA4,0x0B,0x80,0x01,0x3C,0xC8,0x75,0x24,0xA4})
 end
 return {ram=r,h=h,work=work,ready=ready,stage=readString(r+0xB7500,16)or '?'}
end
function S.inspect()
 local c=S.context(false);local r=c.ram;c.values={}
 for _,e in ipairs(S.fields)do c.values[e.key]=u16(r+0xB7510+e.index*2)end
 c.hours=u16(r+0xB75C6);c.seconds=u16(r+0xB75C8);c.frames=u32(r+0xAE160)
 c.playTime=S.formatTime(c.hours,c.seconds)
 c.stageTime=S.formatTime(u16(r+0xB75C2),u16(r+0xB75C4))
 c.lastSaveTime=S.formatTime(u16(r+0xB75CA),u16(r+0xB75CC))
 local level=u16(r+0xB7512);if level&gt;=32768 then level=level-65536 end
 c.difficulty=levels[level]or ('Unknown ('..level..')')
 return c
end
function S.formatTime(hours,seconds)
 return string.format('%02d:%02d:%02d',hours,math.floor(seconds/60),seconds%60)
end
local function log(c,key,before,after,savedBefore,savedAfter)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../logs/statistics-edits-'..S.pid..'.csv','a+'))
  local success,problem=pcall(function()
   if f:seek('end')==0 then assert(f:write('utc,stage,field,before,after,saved_before,saved_after\n'))end
   assert(f:write(table.concat({os.date('!%Y-%m-%dT%H:%M:%SZ'),c.stage,key,before,after,savedBefore,savedAfter},',')..'\n'))
  end)
  f:close();assert(success,problem)
 end)
 if not ok then S.logError=tostring(err)end
end
function S.setCounter(key,value)
 local e
 for _,f in ipairs(S.fields)do if f.key==key then e=f;break end end
 assert(e,'Unknown statistic.')
 value=integer(value,0,32767,e.name)
 local c=S.context(true);local a=c.ram+0xB7510+e.index*2;local before=u16(a)
 local saved=c.ram+0xB6C40+e.index*2;local savedBefore=u16(saved)
 assert(writeSmallInteger(a,value),'Statistic write failed.')
 assert(writeSmallInteger(saved,value),'Saved statistic write failed.')
 local actual=u16(a);assert(actual==value,'Game changed the counter during the edit; refresh and try again.')
 assert(u16(saved)==value,'Saved statistic did not retain the edit.')
 S.status=e.name..': '..before..' -&gt; '..actual..'. Normal tracking continues.'
 log(c,key,before,actual,savedBefore,u16(saved));return actual
end
function S.setTime(hours,minutes,seconds)
 hours=integer(hours,0,9942,'Hours');minutes=integer(minutes,0,59,'Minutes');seconds=integer(seconds,0,59,'Seconds')
 local total=hours*3600+minutes*60+seconds
 assert(total&lt;=math.floor(0x7FFFFFFF/60),'Play time exceeds the signed game-clock limit.')
 local c=S.context(true);local r=c.ram;local oldFrames=u32(r+0xAE160)
 local savedBefore=S.formatTime(u16(r+0xB6CF6),u16(r+0xB6CF8))
 -- The resident clock loads/stores gp+764. In this build it is AE160;
 -- saving also serializes that accumulator. Editing display shorts alone fails.
 fp(r,0x2C550,{0x64,0x07,0x83,0x8F,0x0B,0x80,0x02,0x3C,0x9C,0xE0,0x42,0x8C})
 fp(r,0x2C588,{0x64,0x07,0x83,0xAF})
 assert(writeInteger(r+0xAE160,total*60),'Game-clock write failed.')
 assert(writeSmallInteger(r+0xB75C6,hours),'Play-time hours write failed.')
 assert(writeSmallInteger(r+0xB75C8,minutes*60+seconds),'Play-time seconds write failed.')
 assert(writeSmallInteger(r+0xB6CF6,hours),'Saved play-time hours write failed.')
 assert(writeSmallInteger(r+0xB6CF8,minutes*60+seconds),'Saved play-time seconds write failed.')
 local now=u32(r+0xAE160)
 assert(now&gt;=total*60 and now-total*60&lt;=600,'Clock changed unexpectedly during the edit; refresh and try again.')
 local before=S.formatTime(math.floor(oldFrames/216000),math.floor(oldFrames/60)%3600)
 local after=S.formatTime(hours,minutes*60+seconds)
 S.status='Play time: '..before..' -&gt; '..after..'. Clock keeps running.'
 log(c,'play_time',before,after,savedBefore,S.formatTime(u16(r+0xB6CF6),u16(r+0xB6CF8)));return total
end
MGSStats=S
return S
]====]):sub(2),
 [ [====[mgs-super-rainbow.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- Prototype US-only, normal on-foot Snake. Standalone renderer primitive and
-- detached rainbow controller. No speed, collision, combat or stage writes.
assert(not MGSSuperRainbow,'Retain existing controller for cleanup')
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local G=dofile(dir..'mgs-inventory.lua');local R=G.reader
local A=dofile(dir..'mgs-aura-render.lua')
local S={pid=getOpenedProcessID(),enabled=false,version=1,status='Stopped',retired={},binds=0,updates=0}
local function u32(a)return assert(readInteger(a))&amp;0xffffffff end
local function u16(a)return assert(readSmallInteger(a))&amp;0xffff end
local function ptr(r,p,n)assert(p&gt;=0x80010000 and p+n&lt;=0x80200000,'Render pointer outside RAM');return r+(p&amp;0x1fffff)end
local function hash(s)local n=0;for i=1,#s do n=(((n&lt;&lt;5)|(n&gt;&gt;11))+s:byte(i))&amp;0xffff end;return n end
function S.context()
 assert(getOpenedProcessID()==S.pid,'Attached process changed')
 local c=G.context(true);local r=c.ram
 assert(c.stage:match('^s%d%d%lr?$'),'Enter a normal story stage')
 assert(u32(r+0xAE0A0)==0 and u32(r+0xBFAD0)==0x8003A948 and u32(r+0xBFAD4)==0x8003AA94 and u16(r+0xBFAF2)==0,'Resume normal gameplay and close menus')
 local id=hash(c.stage)
 assert(readString(r+0xADB34,8)==c.stage and u16(r+0xAE138)==id and u16(r+0xB751C)==id and u16(r+0xB7FC8)==id,'Stage transition in progress')
 assert(c.activeGadget~=10 and c.activeGadget~=5 and c.activeGadget~=6,'Remove stealth or vision goggles before aura')
 c.object=ptr(r,u32(r+c.work+0x9c),0x48+16*0x5c)
 assert(u16(c.object+0x2e)==16,'Normal Snake model required')
 c.definition=ptr(r,u32(c.object+0x24),0x20+16*0x58)
 assert(u32(c.definition)==16,'Snake definition differs')
 local q=A.queueState(r);local present=false
 for i=0,q.objs-1 do if u32(r+A.queue+i*4)==0x80000000+c.object-r then present=true end end
 assert(present,'Snake body is not in the renderer queue')
 return c
end
local C=assert(loadfile(dir..'mgs-cosmetic-colors.lua'))({detached=true,context=S.context})
S.color=C;S.renderer=A
local colors={red={255,100,65},yellow={255,235,90},green={100,255,130},cyan={100,255,255},blue={120,150,255},magenta={255,100,245}}
local sequence={'red','yellow','green','cyan','blue','magenta'}
local function atomic(fn)
 pause();local ok,result=pcall(fn);unpause();if not ok then error(result)end;return result
end
local function colorOwner(c)
 local b=C.binding
 if not(b and b.context.ram==c.ram and b.context.work==c.work and b.context.stage==c.stage and b.context.object==c.object and b.context.definition==c.definition)then return false end
 for i,p in ipairs(b.context.parts)do
  local offset=0x48+p.index*0x5c+0x54+((i-1)%2)*4
  if c.ram+(u32(c.object+offset)&amp;0x1fffff)~=p.address then return false end
 end
 return true
end
local function retire(c,b)
 if A.owned(c.ram,b)then
  A.detach(c.ram,b);b.releaseFrame=u32(c.ram+0xAE160)+4;S.retired[#S.retired+1]=b
 end
end
local function cleanup(h)
 for i=#S.retired,1,-1 do local b=S.retired[i]
  if h.ram~=b.ram or not A.owned(h.ram,b)then table.remove(S.retired,i)
  elseif u32(h.ram+0xAE160)&gt;=b.releaseFrame then A.release(h.ram,b);table.remove(S.retired,i)end
 end
end
function S.tick()
 assert(getOpenedProcessID()==S.pid,'Attached process changed')
 local h=R.read();cleanup(h)
 local ready,c=pcall(S.context)
 if not ready then
  if S.binding then A.hide(h.ram,S.binding)end
  S.status='Waiting: '..tostring(c);return
 end
 if not S.enabled then
  if S.binding then retire(c,S.binding);S.binding=nil end
  if C.binding then if colorOwner(c)and u32(c.object+0x28)&amp;8==0 then C.restore()else C.binding=nil end end
  S.status=#S.retired&gt;0 and 'Removing particles after draw buffers drain' or 'Stopped; native colors restored'
  if #S.retired==0 and S.timer then S.timer.destroy();S.timer=nil end
  return
 end
 if C.binding and (not colorOwner(c)or u32(c.object+0x28)&amp;8~=0)then C.binding=nil end
 local now=getTickCount();local name=sequence[math.floor((now-S.started)/400)%6+1]
 -- Acquire a stable shaded packet snapshot before allocating a group.
 if not C.binding or name~=S.colorName then C.apply(name);S.colorName=name end
 local b=S.binding
 if b and not A.owned(c.ram,b)then b=nil;S.binding=nil end
 if b and not A.present(c.ram,b)then retire(c,b);b=nil;S.binding=nil end
 if not b then
  S.serial=(S.serial or 0)+1
  b=A.allocate(c,(S.pid*65537+S.serial)&amp;0xffffffff);S.binding=b;S.binds=S.binds+1
 end
 A.update(c,b,(now-S.started)/1000*1.7,colors[name])
 S.updates=S.updates+1;S.stage=c.stage;S.status='Rainbow + orbiting sparkles: '..c.stage
end
function S.start()
 assert(not S.timer,'Controller already running or removing particles')
 assert(not MGSColorTest or not MGSColorTest.binding and not MGSColorTest.timer,'Restore the earlier tint preview first')
 S.started=getTickCount();S.enabled=true
 -- A snapshot taken during indirect color linking is refused without writes.
 local last
 for attempt=1,20 do
  local ok,result=pcall(function()return atomic(S.tick)end)
  if ok and S.binding then last=nil;break end
  last=result;if S.binding or C.binding then S.enabled=false;error(tostring(last))end
  sleep(25)
 end
 assert(not last,'Could not acquire a stable initial render frame: '..tostring(last))
 local t=createTimer(nil,false);S.timer=t;t.Interval=75
 t.OnTimer=function()
  local ok,err=pcall(function()atomic(S.tick)end)
  if not ok then
   S.status='Waiting / guarded refusal: '..tostring(err);S.lastError=tostring(err)
   -- A loading/scene/packet refusal is retried without adopting stale owners.
   -- The reader and full ownership checks run before every later write.
  end
 end
 t.Enabled=true;return S.status
end
function S.stop()
 S.enabled=false
 local ok,err=pcall(function()atomic(S.tick)end)
 if not ok then S.status='Cleanup waiting for valid US gameplay: '..tostring(err)end
 return S.status
end
MGSSuperRainbow=S
return S
]====]):sub(2),
 [ [====[mgs-super-saiyan.lua]====] ]=([====[!-- Packaged by analysis/build-mgs-fun-stuff.py.
-- Combined normal-US-Snake cosmetic controller. Speed remains quarantined
-- after revision3 failed live validation; never auto-load movement patches.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local P={version=1,features={rainbow=true,sparkles=true,speed=false,hover=false},status='Inactive'}
function P.start(options)
 options=options or{}
 assert(not options.speed,'Speed is quarantined after a failed live test')
 assert(not options.hover,'Hover is not validated')
 local prior=MGSSuperRainbow
 if prior and prior.pid~=getOpenedProcessID()then
  if prior.timer then prior.timer.destroy();prior.timer=nil end
  -- Old-process addresses are never restored into the new process.
  MGSSuperRainbow=nil;prior=nil
 end
 if not prior then prior=dofile(dir..'mgs-super-rainbow.lua')end
 P.cosmetics=prior
 if not prior.enabled then prior.start()end
 P.status='Super Saiyan Snake: rainbow + orbiting sparkles; speed/hover disabled'
 return P.status
end
function P.stop()
 if P.cosmetics then P.cosmetics.stop()end
 P.status='Stopping cosmetics; speed/hover remain disabled';return P.status
end
MGSSuperSaiyan=P
return P
]====]):sub(2),
 [ [====[mgs-toggles.lua]====] ]=([====[!-- Generated by analysis/build-mgs-special-health.py.
-- Optional data-only cheats for the validated US base-game layout.
-- No game code patches, injected calls or debugger attachment.
if MGSToggles then
 assert(MGSToggles.pid==getOpenedProcessID(),'Stop the old controller before changing processes')
 return MGSToggles
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=MGSReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'mgs-reader.lua')end
local T={pid=R.pid,reader=R,version=3,health={enabled=false,requested=false,rebinds=0,status='OFF'},ammo={enabled=false,status='OFF'},stopped=false}
local INV=0x00800000
local MASK=0x0096
local function u16(address)return assert(readSmallInteger(address),'Cannot read 16-bit value')&amp;0xFFFF end
local function u32(address)return assert(readInteger(address),'Cannot read 32-bit value')&amp;0xFFFFFFFF end
local function put16(address,value,mask)
 assert(writeSmallInteger(address,value&amp;0xFFFF),'16-bit write failed')
 if mask~=false then
  mask=mask or 0xFFFF
  assert(u16(address)&amp;mask==(value&amp;mask),'16-bit verification failed')
 end
end
local function put32(address,value,mask)
 assert(writeInteger(address,value&amp;0xFFFFFFFF),'32-bit write failed')
 mask=mask or 0xFFFFFFFF
 assert(u32(address)&amp;mask==(value&amp;mask),'32-bit verification failed')
end
local function put8(address,value)
 assert(writeBytes(address,value&amp;255),'Byte write failed')
 assert(readBytes(address,1)==value,'Byte verification failed')
end
local function fingerprint(address,expected)
 local actual=readBytes(address,#expected,true)
 assert(actual and #actual==#expected,'Protection code unavailable')
 for i,v in ipairs(expected)do assert(actual[i]==v,'Unsupported protection code fingerprint')end
end
local function psx(pointer,size)
 assert(pointer and pointer&gt;=0x80000000 and pointer&lt;0x80200000,'Invalid PlayStation pointer')
 local offset=pointer&amp;0x1FFFFF
 assert(offset+(size or 1)&lt;=0x200000,'PlayStation object exceeds RAM')
 return offset
end
function T.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xADB40)==0 and u32(ram+0xAE1B0)~=0,'Area loading')
 local control=u32(ram+0xAE16C)
 local work=psx(control,0x100)-0x20
 assert(work&gt;=0 and work+0xA24&lt;0x200000,'Invalid Snake actor bounds')
 assert(u32(ram+work+8)==0x8005CE1C and u32(ram+work+0xC)==0x8005D514,'Snake actor is not live')
 assert(u32(ram+0xAE198)==0x80000000+work+0x9C,'Snake body owner mismatch')
 local target=psx(u32(ram+work+0x898),0x48)
 assert(u16(ram+target+2)==1,'Collision target is not on the player side')
 return {h=h,ram=ram,work=work,target=target,status=ram+0xAE1C8}
end
local function sameOwner(c,s)
 return c.ram==s.ram and c.work==s.work and c.target==s.target
end
local function checkCode(ram)
 -- Real set-invulnerability routine: set player bit, set frames, clear mask.
 fingerprint(ram+0x51AB8,{0xC7,0x42,0x01,0x0C,0x80,0x00,0x04,0x3C,0x98,0x08,0x03,0x8E,0x20,0x0A,0x11,0xA2})
 fingerprint(ram+0x51AD0,{0x69,0xFF,0x42,0x30,0x00,0x00,0x62,0xA4})
 fingerprint(ram+0x50B1C,{0x0B,0x80,0x02,0x3C,0xC8,0xE1,0x42,0x8C})
 -- SOCOM firing stores magazine and decreases total ammo at B7532.
 fingerprint(ram+0x67CC0,{0x0B,0x80,0x01,0x3C,0x64,0xE1,0x30,0xA4,0x0B,0x80,0x01,0x3C,0xA4,0xE1,0x24,0xA4,0xFF,0xFF,0x63,0x24,0x00,0x00,0x43,0xA4})
end
local function applyHealth(c,s)
 assert(sameOwner(c,s),'Snake actor/RAM changed; stop and re-enable protection in gameplay')
 -- Match the game's invulnerability state. Zero frames means no expiration.
 local status=u32(c.status)
 if status&amp;INV==0 then put32(c.status,status|INV,INV)end
 if readBytes(c.ram+c.work+0xA20,1)~=0 then put8(c.ram+c.work+0xA20,0)end
 local class=u16(c.ram+c.target)
 if class&amp;MASK~=0 then put16(c.ram+c.target,class&amp;(~MASK&amp;0xFFFF),MASK)end
end
local function restoreHealth(s)
 if not s.owner then return true end
 assert(getOpenedProcessID()==T.pid,'Cannot restore while attached to another process')
 local c=T.context()
 if not sameOwner(c,s.owner)then
  -- The original actor has been replaced. Its old fields are no longer ours
  -- to write; the new actor was not patched by this ownership record.
  s.owner=nil;return true
 end
 -- Restore only our collision-mask bits, preserving unrelated current flags.
 put16(c.ram+c.target,(u16(c.ram+c.target)&amp;(~MASK&amp;0xFFFF))|s.originalMask,MASK)
 put8(c.ram+c.work+0xA20,0)
 put32(c.status,u32(c.status)&amp;(~INV&amp;0xFFFFFFFF),INV)
 s.owner=nil
 return true
end
local function applyAmmo(c)
 local h=c.h
 for i=1,10 do
  local current,capacity=h.ammo[i],h.ammoMax[i]
  -- Leave unowned weapons and undefined capacities alone.
  if current&gt;=0 and capacity&gt;0 and capacity&lt;=32767 and current&lt;capacity then
   put16(c.ram+0xB7532+(i-1)*2,capacity,false)
  end
 end
 -- These three firearms use the shared magazine fields. Never change capacity.
 if h.weapon==0 or h.weapon==1 or h.weapon==9 then
  local capacity=h.magazineMax
  if capacity&gt;0 and capacity&lt;=500 and h.magazine&gt;=0 and h.magazine&lt;capacity then
   local total=h.ammoMax[h.weapon+1]
   if total&gt;0 then put16(c.ram+0xAE164,math.min(capacity,total),false)end
  end
 end
end
function T.disable(kind)
 local s=assert(T[kind],'Unknown option')
 s.enabled=false
 if kind=='health'then s.requested=false end
 if kind=='health'and s.owner then
  local ok,err=pcall(restoreHealth,s)
  if not ok then s.status='RESTORE PENDING: '..tostring(err);return false,s.status end
 end
 s.mode=nil;s.status='OFF'
 return true
end
local function specialRead()
 local h=R.read();h.stage=readString(h.ram+0xB7500,16)
 assert(h.stage and h.stage:match('^[%w_]+$')and #h.stage&lt;=12,'Enter US MGS gameplay')
 return h
end
-- US MGS jeep actor: global vitality refill only; never normal Snake fields.
local function jeepContext()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=specialRead();local r=h.ram
 assert((h.stage=='s19b' or h.stage=='s19br') and h.health&gt;0 and u32(r+0xadb44)==0,'Enter living jeep gameplay')
 assert(u32(r+0xadb40)==0 and u32(r+0xae1b0)~=0,'Jeep area loading')
 assert(u32(r+0xae0a0)==0 and u32(r+0xadb3c)==0x20000000 and u32(r+0xae1c8)==0,'Finish jeep scene or pause')
 assert(u32(r+0xbfad0)==0x8003a948 and u32(r+0xbfad4)==0x8003aa94 and u16(r+0xbfaf2)==0,'Close the menu')
 local work=psx(u32(r+0xae16c),0x100)-0x20
 assert(work&gt;=0x10000 and work+0x100&lt;0x200000,'Jeep actor bounds differ')
 assert(u32(r+work+8)==0x800167fc and u32(r+work+12)==0x800e1180,'Jeep actor identity differs')
 assert(readString(r+0xe1180,10)=='jeep_sne.c','Jeep actor label differs')
 assert(u32(r+0xae198)==0x80000000+work+0x9c,'Jeep body ownership differs')
 for _,p in ipairs({{offset=0x167FC,bytes={232,255,189,39,16,0,191,175,33,40,128,0,55,89,0,12,2,0,4,36,16,0,191,143,24,0,189,39,8,0,224,3}},{offset=0xD79A4,bytes={16,9,67,142,11,128,2,60,38,117,66,148,0,0,0,0,38,0,98,164,11,128,8,60,38,117,8,37,0,0,2,133,60,9,67,142,16,9,69,142,35,16,67,0,38,0,164,132,11,128,3,60,40,117,99,132,33,32,130,0,42,16,100,0,3,0,64,16,0,20,4,0,33,32,96,0,0,20,4,0,3,20,2,0,38,0,164,164,60,9,66,174,69,0,64,28,0,0,2,165}},{offset=0xD7AA8,bytes={11,128,2,60,60,219,66,140,0,64,3,60,36,16,67,0,21,0,64,20,1,0,2,36,11,128,1,60,38,117,32,164,59,179,0,12,0,0,0,0,33,32,0,0,26,0,5,36,255,255,2,36,11,128,1,60,68,219,34,172,1,0,2,36,202,209,0,12,80,9,66,174,11,128,2,60,60,219,66,140,0,16,3,60,37,16,67,0,11,128,1,60,60,219,34,172,198,94,3,8,0,0,0,0,11,128,1,60,38,117,34,164}}})do fingerprint(r+p.offset,p.bytes)end
 checkCode(r)
 return {h=h,ram=r,work=work}
end
local function applyJeepHealth()
 local c=jeepContext();local fresh=jeepContext()
 assert(c.ram==fresh.ram and c.work==fresh.work and c.h.maximum==fresh.h.maximum,'Jeep owner changed')
 -- The jeep uses global vitality. It has no normal Snake target/mask layout.
 if fresh.h.health&lt;fresh.h.maximum then put16(fresh.ram+0xb7526,fresh.h.maximum)end
 local s=T.health
 if s.mode~='jeep' then s.rebinds=s.rebinds+1 end
 s.owner=nil;s.resumeOwned=nil;s.mode='jeep';s.requested=true;s.enabled=true
 s.status='ON - jeep health refill | normal invulnerability resumes after jeep'
 return true
end

-- rope.c owns a separate TARGET at work+804. Its Act copies target+26 to
-- GM_Vitality; refilling GM_Vitality alone cannot prevent its death branch.
local ropeProofs={{offset=0xCAC6C,bytes={176,255,189,39,68,0,177,175,33,136,128,0,72,0,178,175,156,0,50,38,11,128,2,60,60,219,66,140,8,0,3,60,76,0,191,175,64,0,176,175,37,16,67,0,11,128,1,60,60,219,34,172,11,128,6,60,136,225,198,36,35,0,34,138,32,0,34,154,39,0,35,138,36,0,35,154,3,0,194,168,0,0,194,184,7,0,195,168,4,0,195,184,135,218,0,12,33,32,64,2,4,8,34,142,0,0,0,0,38,0,66,132,0,0,0,0,5,0,64,28,32,0,48,38,117,0,34,146}},{offset=0xCAF60,bytes={4,8,34,142,0,0,0,0,38,0,66,148,11,128,3,60,38,117,99,36,0,0,98,164,0,20,2,0,2,0,65,4,0,0,0,0,0,0,96,164,213,42,3,12,33,32,32,2}},{offset=0xC70EC,bytes={224,255,189,39,16,0,176,175,33,128,128,0,28,0,191,175,24,0,178,175,20,0,177,175,112,15,3,142,0,0,0,0,0,33,98,48,153,0,64,20,0,128,98,48,4,8,17,142,0,0,0,0,6,0,50,150,54,0,64,16,4,0,66,50}},{offset=0xC7280,bytes={6,0,34,150,40,0,32,166,42,0,32,166,251,255,66,48,6,0,34,166,11,128,5,60,236,218,165,36,3,0,162,136,0,0,162,152,7,0,163,136,4,0,163,152,47,0,34,170,44,0,34,186,51,0,35,170,48,0,35,186,38,0,34,134,0,0,0,0,14,0,64,28,0,0,0,0,11,128,3,60,60,219,99,140,13,128,2,60,144,168,66,36,172,14,2,174,176,14,0,174,190,14,0,166,188,14,0,166,0,32,99,52,11,128,1,60,60,219,35,172,222,28,3,8,0,0,0,0}},{offset=0xC706C,bytes={32,0,2,36,124,15,130,172,112,15,130,140,4,8,131,140,0,128,66,52,112,15,130,172,0,0,98,148,0,0,0,0,235,255,66,48,8,0,224,3,0,0,98,164,112,15,130,140,4,8,131,140,124,15,133,172,0,128,66,52,112,15,130,172,0,0,98,148,0,0,0,0,235,255,66,48,8,0,224,3,0,0,98,164}}}
local ROPE_MASK=0x14 -- Native TARGET_POWER | TARGET_SEEK.
local function ropeContext()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=specialRead();local r=h.ram
 assert(h.stage=='s11d'and h.health&gt;0 and u32(r+0xadb44)==0,'Enter living rappel gameplay')
 assert(u32(r+0xadb40)==0 and u32(r+0xae1b0)~=0 and u32(r+0xae0a0)==0,'Rappel loading or paused')
 assert(u32(r+0xadb3c)==0x20488000 and u32(r+0xae1c8)==0,'Finish the rappel scene')
 assert(u32(r+0xbfad0)==0x8003a948 and u32(r+0xbfad4)==0x8003aa94 and u16(r+0xbfaf2)==0,'Close the menu')
 local work=psx(u32(r+0xae16c),0x10)-0x20
 assert(work&gt;=0x10000 and work+0x1098&lt;=0x200000,'Rappel actor bounds differ')
 assert(u32(r+work+8)==0x800cac6c and u32(r+work+12)==0x800cafac and u32(r+work+20)==0x800d4e0c,'Rappel actor identity differs')
 assert(readString(r+0xd4e0c,6)=='rope.c'and u32(r+0xae198)==0x80000000+work+0x9c,'Rappel body/label differs')
 for _,p in ipairs(ropeProofs)do fingerprint(r+p.offset,p.bytes)end
 checkCode(r)
 local target=psx(u32(r+work+0x804),0x48)
 local hp=u16(r+target+0x26)
 assert(u16(r+target+2)==1 and hp&gt;0 and hp&lt;=h.maximum,'Rappel target side/health invalid or depleted')
 local state=u32(r+work+0xeac)
 assert(state&gt;=0x800c6524 and state&lt;0x800cac6c and state~=0x800ca7c4 and state~=0x800ca890 and state~=0x800cab04,'Rappel death/unsupported state')
 return {h=h,ram=r,work=work,target=target}
end
local function ropeSame(c,s)return c.ram==s.ram and c.work==s.work and c.target==s.target end
local function applyRopeHealth()
 local c=ropeContext();local fresh=ropeContext()
 assert(ropeSame(c,fresh)and c.h.maximum==fresh.h.maximum,'Rappel owner changed')
 local s=T.health;local owner=s.ropeOwner
 if not owner or not ropeSame(fresh,owner)then
  owner={ram=fresh.ram,work=fresh.work,target=fresh.target,mask=u16(fresh.ram+fresh.target)&amp;ROPE_MASK}
  s.ropeOwner=owner;s.rebinds=s.rebinds+1
 end
 local a=fresh.ram+fresh.target
 if u16(a)&amp;ROPE_MASK~=0 then put16(a,u16(a)&amp;(~ROPE_MASK&amp;0xffff),ROPE_MASK)end
 -- Cancel already-delivered damage, then heal the authoritative private HP.
 if u16(a+6)&amp;4~=0 then put16(a+6,u16(a+6)&amp;0xfffb,4)end
 for _,o in ipairs({0x28,0x2a})do if u16(a+o)~=0 then put16(a+o,0)end end
 if u16(a+0x26)~=fresh.h.maximum then put16(a+0x26,fresh.h.maximum)end
 if fresh.h.health~=fresh.h.maximum then put16(fresh.ram+0xb7526,fresh.h.maximum)end
 s.owner=nil;s.resumeOwned=nil;s.mode='rappel';s.requested=true;s.enabled=true
 s.status='ON - rappel target immunity + private health protection'
 return true
end
local function restoreRopeHealth()
 local s=T.health;local owner=s.ropeOwner;if not owner then return true end
 assert(getOpenedProcessID()==T.pid,'Original process required for rappel restoration')
 local h=specialRead();local p=u32(h.ram+0xae16c)
 if h.ram~=owner.ram or h.stage~='s11d'or p~=0x80000000+owner.work+0x20 or u32(h.ram+owner.work+8)~=0x800cac6c then
  s.ropeOwner=nil;return true -- Replaced actors do not own these fields.
 end
 local c=ropeContext();assert(ropeSame(c,owner),'Rappel target changed before restoration')
 local a=c.ram+c.target
 put16(a,(u16(a)&amp;(~ROPE_MASK&amp;0xffff))|owner.mask,ROPE_MASK)
 s.ropeOwner=nil;return true
end
local disableNormal=T.disable
function T.disable(kind)
 if kind=='health'then
  T.health.requested=false;T.health.enabled=false
  local ok,err=pcall(restoreRopeHealth)
  if not ok then T.health.status='RESTORE PENDING: '..tostring(err);return false,T.health.status end
 end
 return disableNormal(kind)
end
local function applySpecialHealth()
 local h=specialRead()
 if h.stage=='s11d'then return applyRopeHealth()end
 local ok=applyJeepHealth();T.health.ropeOwner=nil;return ok
end

function T.enable(kind)
 assert(not T.stopped,'Reload the stopped controller')
 local s=assert(T[kind],'Unknown option')
 if s.enabled then return true end
 assert(not s.owner,'Finish pending health restoration before re-enabling')
 local ok,c=pcall(T.context)
 if not ok then
  if kind=='health'then return applySpecialHealth()end
  error(c)
 end
 checkCode(c.ram)
 assert(c.h.health&gt;0 and u32(c.ram+0xADB44)==0,'Enter normal living gameplay before enabling')
 if kind=='health'then
  local existing=u32(c.status)&amp;INV~=0
  local frames=assert(readBytes(c.ram+c.work+0xA20,1),'Cannot read invulnerability frames')
  assert(not existing or (frames&gt;0 and frames&lt;128)or s.resumeOwned,'An existing permanent invulnerability state is active; leave it unchanged')
  -- A normal hit's temporary immunity can be extended. OFF then performs its
  -- normal expiration mask, rather than preserving that temporary no-hit mask.
  s.originalMask=existing and MASK or (u16(c.ram+c.target)&amp;MASK)
  s.owner={ram=c.ram,work=c.work,target=c.target}
  local ok,err=pcall(function()
   applyHealth(c,s.owner)
   -- Synchronize the three health values once; no health-value freeze loop.
   put16(c.ram+c.target+0x26,c.h.maximum)
   put16(c.ram+c.work+0xA1E,c.h.maximum)
   put16(c.ram+0xB7526,c.h.maximum)
  end)
  if not ok then
   local restored,restoreError=pcall(restoreHealth,s)
   s.status=restored and ('OFF: '..tostring(err))or ('RESTORE PENDING: '..tostring(restoreError))
   error(s.status)
  end
  s.mode='normal';s.status='ON - native invulnerability + initial heal'
  s.requested=true;s.resumeOwned=nil
 elseif kind=='ammo'then
  applyAmmo(c);s.ram=c.ram;s.work=c.work
  s.status='ON - owned ammo/magazines replenish'
 else error('Unknown option')end
 s.enabled=true
 return true
end
function T.tick()
 if T.stopped then return end
 if not T.health.requested and not T.ammo.enabled and not T.health.owner and not T.health.ropeOwner then return end
 -- Retry our own pending restoration when gameplay becomes readable again.
 if not T.health.requested and (T.health.owner or T.health.ropeOwner)then T.disable('health')end
 if not T.health.requested and not T.ammo.enabled then return end
 local ok,c=pcall(T.context)
 if not ok then
  local ammoWasEnabled=T.ammo.enabled
  T.health.enabled=false;T.ammo.enabled=false
  if ammoWasEnabled then T.ammo.status='OFF: '..tostring(c)end
  if T.health.requested then T.health.status='WAITING FOR AREA: '..tostring(c)
  elseif T.health.owner then T.health.status='RESTORE PENDING: '..tostring(c)end
  if T.health.requested then
   local applied,err=pcall(applySpecialHealth)
   if not applied then T.health.status='WAITING FOR AREA: '..tostring(err)end
  end
  return
 end
 T.health.ropeOwner=nil -- Normal actor identity proves special actor replacement.
 if T.health.requested then
  local rebound=T.health.owner and not sameOwner(c,T.health.owner)
  if rebound then
   T.health.resumeOwned=T.health.owner.ram==c.ram
   T.health.owner=nil;T.health.enabled=false
  end
  local applied,err=pcall(function()
   if not T.health.owner then T.health.enabled=false;T.enable('health')
   else applyHealth(c,T.health.owner)end
  end)
  if not applied then
   T.health.enabled=false;T.health.status='WAITING FOR AREA: '..tostring(err)
  else
   if rebound then T.health.rebinds=T.health.rebinds+1 end
   T.health.enabled=true;T.health.status='ON - native invulnerability | area rebinds '..T.health.rebinds
  end
 end
 if T.ammo.enabled then
  if c.ram~=T.ammo.ram or c.work~=T.ammo.work then
   T.ammo.enabled=false;T.ammo.status='OFF: actor/RAM changed; re-enable in gameplay'
  else
   local applied,err=pcall(applyAmmo,c)
   if not applied then T.ammo.enabled=false;T.ammo.status='OFF: '..tostring(err)end
  end
 end
end
function T.stopAll()
 local restored=T.disable('health');T.disable('ammo')
 if not restored then return false,T.health.status end
 T.stopped=true;T.timer.Enabled=false;T.timer.destroy();T.timer=nil
 if MGSToggles==T then MGSToggles=nil end
 return true
end
T.timer=createTimer(nil,false);T.timer.Interval=50;T.timer.OnTimer=T.tick;T.timer.Enabled=true
MGSToggles=T
return T
]====]):sub(2),
 [ [====[room-loader-panel.lua]====] ]=([====[!-- Generated by analysis/build-mgs-rooms.py.
-- Native CE dashboard. Reading/filtering/selecting a destination never writes.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSRoomPanel and MGSRoomPanel.pid==getOpenedProcessID()and MGSRoomPanel.loader==MGSRoomLoader then MGSRoomPanel.show();return MGSRoomPanel end
if MGSRoomPanel then MGSRoomPanel.stop()end
local W=dofile(dir..'mgs-room-loader.lua');local P={pid=W.pid,loader=W,stopped=false,visible={}}
local form=createForm(false);P.form=form;form.Caption='MGS - Room &amp; Encounter Loader'
form.Width=850;form.Height=700;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local function label(x,y,text,width,height)
 local l=createLabel(form);l.Left=x;l.Top=y;l.Caption=text
 if width then l.AutoSize=false;l.Width=width;l.Height=height or 24;l.WordWrap=true end
 return l
end
label(16,12,'ROOM &amp; ENCOUNTER LOADER')
local current=label(16,44,'Reading MGS...',800,36);P.current=current
label(16,91,'Show');local group=createComboBox(form);P.group=group
group.Left=66;group.Top=86;group.Width=208;group.Style='csDropDownList'
for _,name in ipairs({'All rooms &amp; encounters','Story rooms','Encounters','Scenes / variants'})do group.Items.add(name)end;group.ItemIndex=0
label(292,91,'Search');local search=createEdit(form);P.search=search;search.Left=355;search.Top=86;search.Width=460
local list=createListBox(form);P.list=list;list.Left=16;list.Top=128;list.Width=800;list.Height=258
local details=label(16,399,'Select a destination.',800,74);P.details=details
local load=createButton(form);P.loadButton=load;load.Left=16;load.Top=480;load.Width=238;load.Height=34;load.Caption='Load selected room'
local back=createButton(form);P.backButton=back;back.Left=270;back.Top=480;back.Width=238;back.Height=34;back.Caption='Load previous room'
local refresh=createButton(form);refresh.Left=524;refresh.Top=480;refresh.Width=142;refresh.Height=34;refresh.Caption='Refresh'
local status=createMemo(form);P.memo=status;status.Left=16;status.Top=528;status.Width=800;status.Height=106;status.ReadOnly=true;status.WordWrap=true;status.ScrollBars='ssVertical'
label(16,643,'MGS story game only. Arenas do not reset defeated bosses. Other discs / scenes may need game-driven transitions.',800,36)
local function errorText(e)return tostring(e):match(': ([^\r\n]+)$')or tostring(e)end
function P.selected()return P.visible[list.ItemIndex+1]end
local function describe()
 local e=P.selected()
 details.Caption=e and (e.name..'  ['..e.id..']'..(e.encounter and '\r\nEncounter: '..e.encounter or '')..'\r\n'..(e.spawn_verified and 'Interior placement checked. 'or e.tested_load and 'Load tested in live MGS. 'or 'Destination load untested. ')..e.note)or 'Select a destination.'
end
function P.filter()
 local old=P.selected();local wanted=group.Items[group.ItemIndex];local query=search.Text:lower()
 list.Items.clear();P.visible={}
 for _,e in ipairs(W.catalog)do
  local haystack=(e.id..' '..e.name..' '..(e.encounter or '')):lower()
  if (group.ItemIndex==0 or e.group==wanted)and haystack:find(query,1,true)then
   P.visible[#P.visible+1]=e
   list.Items.add(string.format('%s   %s%s',e.id,e.name,e.encounter and ('  |  '..e.encounter)or ''))
  end
 end
 list.ItemIndex=#P.visible&gt;0 and 0 or -1
 if old then for i,e in ipairs(P.visible)do if e.id==old.id then list.ItemIndex=i-1;break end end end
 describe();if P.tick then P.tick()end
end
function P.tick()
 if P.stopped then return end
 if getOpenedProcessID()~=P.pid then P.stop();return end
 local ok,s=pcall(W.poll);P.state=ok and s or nil
 local e=P.selected();load.Enabled=ok and s.ready and e~=nil or false
 back.Enabled=ok and ((s.ready and s.previous~=nil)or s.canRecover)or false
 back.Caption=ok and s.canRecover and 'Return from empty scene'or 'Load previous room'
 if ok then
  current.Caption=string.format('Current room: %s  |  Snake HP: %d / %d  |  %s',s.stage,s.health,s.maximum,s.ready and 'Ready to load'or 'Waiting for gameplay')
 else current.Caption='Waiting for MGS gameplay'end
 local text={P.error and ('Action: '..P.error)or W.status}
 if not ok then text[#text+1]=errorText(s)elseif s.reason then text[#text+1]=errorText(s.reason)end
 if W.previous then text[#text+1]='Previous room: '..W.previous..' (room only; entry position follows game rules)'end
 if W.logError then text[#text+1]='Log: '..errorText(W.logError)end
 status.Lines.Text=table.concat(text,'\r\n')
end
local function act(fn)
 local ok,err=pcall(fn);P.error=not ok and errorText(err)or nil;P.tick()
end
load.OnClick=function()act(function()local e=assert(P.selected(),'Select a destination');W.request(e.id)end)end
back.OnClick=function()act(function()if P.state and P.state.canRecover then W.recoverPrevious()else W.returnPrevious()end end)end
refresh.OnClick=function()P.error=nil;P.tick()end
list.OnSelectionChange=function()describe();P.tick()end
group.OnChange=P.filter;search.OnChange=P.filter
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if W.stopOffice then W.stopOffice('cancelled','Dashboard closed')end
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if MGSRoomPanel==P then MGSRoomPanel=nil end
 local row=getAddressList().getMemoryRecordByID(12);if row and row.Active then row.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
P.timer=createTimer(form,false);P.timer.Interval=500;P.timer.OnTimer=P.tick
MGSRoomPanel=P;P.filter();P.tick();P.timer.Enabled=true;P.show()
return P
]====]):sub(2),
 [ [====[Special-Missions/dashboard.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- CE-side window and change log. All game access is through read-only reads.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if SPMDashboard then
 SPMDashboard.stop()
 assert(not SPMDashboard,'Close the previous dashboard before reloading')
end
local R=dofile(dir..'spm-reader.lua')
local D={reader=R,pid=R.pid,samples=0,changes=0,errors=0,label='baseline',stopped=false}
local logPath=dir..'../../logs/spm-state-'..R.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'.csv'
local csv=assert(io.open(logPath,'w'));D.logPath=logPath
local columns={'utc','label','health','max_health','weapon_id','item_id','total_ammo','ammo_capacity','magazine','mag_capacity','alert_mode','alert_level','ration','ration_capacity'}
for i=1,10 do columns[#columns+1]='ammo_'..(i-1)end
csv:write(table.concat(columns,',')..'\n');csv:flush()
local form=createForm(false);D.form=form;form.Caption='Special Missions - Monitor';form.Width=660;form.Height=700
form.Position='poScreenCenter'
local memo=createMemo(form);D.memo=memo;memo.Align='alClient';memo.ReadOnly=true;memo.ScrollBars='ssVertical';memo.WordWrap=false
memo.Font.Name='Consolas';memo.Font.Size=11
local function value(v)return v==nil and '--'or tostring(v)end
local function csvValue(v)return '"'..tostring(v or ''):gsub('"','""')..'"'end
function D.mark(label)
 assert(type(label)=='string'and #label&lt;=80,'Short test label required')
 D.label=label;D.last=nil
end
local function display(h)
 local rows={'READ-ONLY MONITOR | Steam build 20872173 | European Special Missions',
  'Special Missions port: readings checked; gameplay effects need VR-specific validation','',
  string.format('Health       %d / %d (%.1f%%)',h.health,h.maximum,100*h.health/h.maximum),
  'Weapon       '..h.weaponName,
  'Total ammo   '..value(h.ammoSelected)..' / '..value(h.ammoSelectedMax),
  'Magazine     '..((h.weapon==0 or h.weapon==1)and (h.magazine..' / '..h.magazineMax)or 'N/A')}
 -- The inventory count includes rounds in the magazine; it is not spare ammo.
 rows[#rows+1]='Rations      '..h.ration..' / '..h.rationMax
 rows[#rows+1]='';rows[#rows+1]='Alert mode   '..h.alertName..' ('..h.alertMode..')'
 rows[#rows+1]='Alert level  '..h.alertLevel..' (raw; not assumed seconds/percent)'
 rows[#rows+1]='';rows[#rows+1]='Inventory ammo (total / capacity)'
 for i,name in ipairs(R.weapons)do
  rows[#rows+1]=string.format('  %-15s %s',name,h.ammo[i]&lt;0 and 'Not owned'or (h.ammo[i]..' / '..h.ammoMax[i]))
 end
 rows[#rows+1]='';rows[#rows+1]='Sample every 100 ms | F7 hide/show | Close to stop'
 rows[#rows+1]='Monitor reads only. Optional cheats are separate CT entries.'
 if SPMToggles then
  rows[#rows+1]='Health protection: '..SPMToggles.health.status
  rows[#rows+1]='Unlimited ammo: '..SPMToggles.ammo.status
 end
 if SPMNoAlert then rows[#rows+1]='No alert: '..SPMNoAlert.status end
 rows[#rows+1]='Test: '..D.label..' | samples '..D.samples..' | changes '..D.changes
 if D.logError then rows[#rows+1]='Logging stopped: '..D.logError end
 memo.Lines.Text=table.concat(rows,'\r\n')
end
function D.tick()
 if D.stopped then return end
 local ok,h=pcall(R.read)
 if not ok then
  D.state=nil;D.errors=D.errors+1;D.error=tostring(h)
  memo.Lines.Text='READ ONLY | Waiting for valid gameplay\r\n'..D.error..'\r\nPrevious values cleared.'
  return
 end
 D.state=h;D.error=nil;D.samples=D.samples+1
 local fields={D.label,h.health,h.maximum,h.weapon,h.item,value(h.ammoSelected),value(h.ammoSelectedMax),h.magazine,h.magazineMax,h.alertMode,h.alertLevel,h.ration,h.rationMax}
 for i=1,10 do fields[#fields+1]=h.ammo[i]end
 local row={};for _,v in ipairs(fields)do row[#row+1]=csvValue(v)end;row=table.concat(row,',')
 if row~=D.last then
  D.changes=D.changes+1;D.last=row
  if csv then
   local logged,err=pcall(function()
    assert(csv:write(os.date('!%Y-%m-%dT%H:%M:%SZ')..','..row..'\n'));assert(csv:flush())
    if csv:seek()&gt;10*1024*1024 then csv:close();csv=nil;D.logError='10 MiB log limit reached'end
   end)
   if not logged then D.logError=tostring(err);pcall(function()csv:close()end);csv=nil end
  end
 end
 display(h)
end
function D.stop(closing)
 if D.stopped then return true end
 D.stopped=true
 if D.timer then D.timer.Enabled=false;D.timer.destroy();D.timer=nil end
 if D.hotkey then D.hotkey.destroy();D.hotkey=nil end
 if csv then csv:close();csv=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if SPMDashboard==D then SPMDashboard=nil end
 -- Closing the diagnostic window affects only its own CT entry.
 local r=getAddressList().getMemoryRecordByID(701)
 if r and r.Description:match('^Dashboard')and r.Active then r.Active=false end
 return true
end
form.OnClose=function()local ok=D.stop(true);return ok and caFree or caNone end
D.hotkey=createHotkey(function()form.Visible=not form.Visible end,0x76)
local timer=createTimer(form,false);D.timer=timer;timer.Interval=100;timer.OnTimer=D.tick
SPMDashboard=D;D.tick();timer.Enabled=true;form.show()
return D
]====]):sub(2),
 [ [====[Special-Missions/guard-state-panel.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if SPMGuardStatePanel and SPMGuardStatePanel.pid==getOpenedProcessID()then SPMGuardStatePanel.show();return SPMGuardStatePanel end
if SPMGuardStatePanel then SPMGuardStatePanel.stop()end
local A=dofile(dir..'spm-guard-state.lua')
local C=dofile(dir..'spm-guard-proximity.lua')
local P={pid=A.pid,actions=A,stopped=false}
local f=createForm(false);P.form=f;f.Caption='Special Missions - Guard state'
f.Width=760;f.Height=655;f.Position='poScreenCenter';f.Font.Name='Segoe UI';f.Font.Size=10
local function label(y,s)
 local v=createLabel(f);v.Left=16;v.Top=y;v.AutoSize=false;v.Width=720;v.Height=40;v.WordWrap=true;v.Caption=s;return v
end
label(12,'One-shot actions for standard guards loaded in the current area.')
label(48,'Knockout preserves health. Extended knockout delays recovery. Kill follows normal death logic and can increase the kill count.')
label(94,'Busy, already down, and unsupported guards are skipped. Cameras, bosses, civilians and Snake are excluded.')
local info=label(138,'');info.Height=48
local memo=createMemo(f);memo.Left=16;memo.Top=266;memo.Width=720;memo.Height=160;memo.ReadOnly=true;memo.ScrollBars='ssVertical'
local status=label(435,'');status.Height=60
local extended=createCheckBox(f);extended.Left=16;extended.Top=190;extended.Caption='Extended knockout (~60 seconds)';extended.Checked=true
local dl=createLabel(f);dl.Left=332;dl.Top=194;dl.Caption='Delay (seconds):'
local delay=createEdit(f);delay.Left=459;delay.Top=189;delay.Width=46;delay.Text='5'
local cancel=createButton(f);cancel.Left=535;cancel.Top=186;cancel.Width=201;cancel.Height=28;cancel.Caption='Cancel scheduled action';cancel.Enabled=false
local buttons={}
local function button(x,width,text,fn)
 local b=createButton(f);b.Left=x;b.Top=225;b.Width=width;b.Height=30;b.Caption=text;b.OnClick=fn;return b
end
function P.refresh()
 if P.stopped then return end
 local ok,c=pcall(A.inspect);P.state=ok and c or nil
 buttons[1].Enabled=ok and c.eligible&gt;0 and not P.pending or false;buttons[2].Enabled=buttons[1].Enabled
 local lines={}
 if ok then
  info.Caption=string.format('Area: %s | Loaded: %d | Ready: %d | Knocked out: %d | Dead: %d | Busy: %d',c.stage,c.total,c.eligible,c.knockedOut,c.dead,c.skipped)
  for _,g in ipairs(c.guards)do lines[#lines+1]=string.format('Guard %d | HP %d | stun %d | %s',g.actor.slot,g.hp,g.faint,g.eligible and 'Ready'or g.reason)end
  if c.reason then lines[#lines+1]=c.reason end
 else info.Caption='Waiting for supported gameplay.';lines[1]=tostring(c)end
 memo.Lines.Text=table.concat(lines,'\r\n');status.Caption=P.error or A.status
 if A.logError then status.Caption=status.Caption..' Log: '..A.logError end
end
local function cancelPending()
 if P.pending then P.pending.Enabled=false;P.pending.destroy();P.pending=nil end;cancel.Enabled=false
end
cancel.OnClick=function()cancelPending();P.error=nil;A.status='Scheduled action cancelled.';P.refresh()end
local function action(mode)
 P.error=nil
 local ok,err=pcall(function()
  local seconds=tonumber(delay.Text)
  assert(seconds and seconds==math.floor(seconds)and seconds&gt;=0 and seconds&lt;=15,'Delay must be 0..15 seconds.')
  local armed=A.inspect();local long=extended.Checked
  local function execute()
   cancelPending()
   local success,result=pcall(function()
    local c=A.inspect();assert(c.ram==armed.ram and c.stage==armed.stage,'Area changed; scheduled action cancelled.')
    local outcome=A.apply(mode)
    if mode=='knockout'and long then A.extendKnockout(outcome,1500)end
    return outcome
   end)
   P.error=not success and tostring(result)or nil;P.refresh()
  end
  cancelPending()
  if seconds==0 then execute();return end
  local timer=createTimer(nil,false);P.pending=timer;timer.Interval=1000;cancel.Enabled=true
  A.status=mode..' in '..seconds..' seconds. Switch back to the game.'
  timer.OnTimer=function()
   seconds=seconds-1
   if seconds&lt;=0 then execute()else status.Caption=mode..' in '..seconds..' seconds. Switch back to the game.'end
  end
  timer.Enabled=true
 end)
 P.error=not ok and tostring(err)or P.error;P.refresh()
end
buttons[1]=button(16,245,'Knock out loaded guards',function()action('knockout')end)
buttons[2]=button(275,245,'Kill loaded guards',function()action('kill')end)
button(535,201,'Refresh (read-only)',function()P.error=nil;P.refresh()end)
label(502,'Proximity: enable the VR knockout or kill checkbox. Only one mode runs at a time.')
local rl=createLabel(f);rl.Left=16;rl.Top=550;rl.Caption='Radius (game units):'
local radius=createEdit(f);radius.Left=178;radius.Top=545;radius.Width=80;radius.Text=tostring(C.radius)
local applyRadius=createButton(f);applyRadius.Left=275;applyRadius.Top=543;applyRadius.Width=150;applyRadius.Height=28;applyRadius.Caption='Apply radius'
local stopAuto=createButton(f);stopAuto.Left=445;stopAuto.Top=543;stopAuto.Width=165;stopAuto.Height=28;stopAuto.Caption='Stop proximity'
local autoStatus=label(583,'');autoStatus.Height=54
applyRadius.OnClick=function()
 local ok,err=pcall(C.setRadius,radius.Text);P.error=not ok and tostring(err)or nil;P.refresh()
end
stopAuto.OnClick=function()C.disable();P.error=nil;P.refresh()end
local statusTimer=createTimer(f,false);P.statusTimer=statusTimer;statusTimer.Interval=500
statusTimer.OnTimer=function()autoStatus.Caption=C.status end;statusTimer.Enabled=true;autoStatus.Caption=C.status
function P.show()f.show()end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 cancelPending();if A.extension then A.extension.stop()end
 if P.statusTimer then P.statusTimer.Enabled=false;P.statusTimer.destroy();P.statusTimer=nil end
 if not closing then f.OnClose=nil;f.destroy()end
 if SPMGuardStatePanel==P then SPMGuardStatePanel=nil end
 local row=getAddressList().getMemoryRecordByID(709)
 if row and row.Description:match('^Guard state')and row.Active then row.Active=false end
 return true
end
f.OnClose=function()P.stop(true);return caFree end
SPMGuardStatePanel=P;P.refresh();P.show();return P
]====]):sub(2),
 [ [====[Special-Missions/inventory-panel.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Inventory picker. Opening/refreshing this window only reads game state.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if SPMInventoryPanel and SPMInventoryPanel.pid==getOpenedProcessID()then
 SPMInventoryPanel.show();return SPMInventoryPanel
end
if SPMInventoryPanel then SPMInventoryPanel.stop()end
local G=dofile(dir..'spm-inventory.lua')
local P={pid=G.pid,inventory=G,stopped=false}
local form=createForm(false);P.form=form;form.Caption='Special Missions - Weapon &amp; Gadget Selector'
form.Width=750;form.Height=675;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local title=createLabel(form);title.Left=16;title.Top=10
title.Caption='Equipment grants. Mission resources may limit usable equipment.'
local function label(parent,x,y,text)
 local l=createLabel(parent);l.Left=x;l.Top=y;l.Caption=text;return l
end
local function button(parent,x,y,text,action)
 local b=createButton(parent);b.Left=x;b.Top=y;b.Width=178;b.Height=30;b.Caption=text;b.OnClick=action;return b
end
local function displayName(kind,id)
 if id&lt;0 then return 'None'end
 local list=kind=='weapon'and G.weapons or G.gadgets
 return list[id+1]and list[id+1].name or '?'
end
local function errorText(err)return tostring(err):match(': ([^\r\n]+)$')or tostring(err)end
local rows={}
local function selected(row)return row.list[row.combo.ItemIndex+1]end
local function act(row,equipping)
 local e=assert(selected(row),'Select equipment')
 local ok,err=pcall(G.grant,row.kind,e.id,row.amount.Text,equipping)
 P.error=not ok and errorText(err)or nil
 if ok then G.status=e.name..(equipping and ' added; equipment switch requested.'or ' added to inventory.')end
 P.tick()
end
local function group(kind,y,caption,list)
 local box=createGroupBox(form);box.Left=12;box.Top=y;box.Width=710;box.Height=170;box.Caption=caption
 local row={kind=kind,list=list,group=box};rows[#rows+1]=row
 local combo=createComboBox(box);row.combo=combo;combo.Left=12;combo.Top=24;combo.Width=325;combo.Style='csDropDownList'
 for _,e in ipairs(list)do combo.Items.add(e.name)end
 row.amountLabel=label(box,355,27,kind=='weapon'and 'Ammo stock' or 'Stock')
 local amount=createEdit(box);row.amount=amount;amount.Left=475;amount.Top=22;amount.Width=95
 row.add=button(box,12,64,'Add to inventory',function()act(row,false)end)
 row.equip=button(box,200,64,'Add + equip',function()act(row,true)end)
 row.unequip=button(box,388,64,'Unequip',function()
  local ok,err=pcall(G.equip,kind,-1);P.error=not ok and errorText(err)or nil;P.tick()
 end)
 local info=label(box,12,105,'');row.info=info;info.AutoSize=false;info.WordWrap=true;info.Width=678;info.Height=53
 combo.OnChange=function()
  local e=selected(row);if e then amount.Text=tostring(e.stock or 1)end
  P.error=nil;if P.tick then P.tick()end
 end
 combo.ItemIndex=0;amount.Text=tostring(list[1].stock or 1)
 return row
end
P.weapon=group('weapon',40,'Weapons - full catalog',G.weapons)
P.gadget=group('gadget',220,'Gadgets and items - full catalog',G.gadgets)
local help=label(form,16,399,'Added equipment stays in inventory when this window closes.')
local memo=createMemo(form);P.memo=memo;memo.Left=12;memo.Top=425;memo.Width=710;memo.Height=195
memo.ReadOnly=true;memo.WordWrap=true;memo.ScrollBars='ssVertical';memo.Font.Name='Consolas';memo.Font.Size=10
function P.tick()
 if P.stopped then return end
 local ok,c=pcall(G.inspect);P.state=ok and c or nil
 for _,row in ipairs(rows)do
  local e=selected(row);local ready=ok and c.ready and e~=nil
  row.add.Enabled=not not ready;row.equip.Enabled=ready and e.equipable~=false or false
  row.unequip.Enabled=not not ready
  row.amount.Enabled=ready and (row.kind=='weapon'or e.kind~=nil)or false
  row.amountLabel.Caption=row.kind=='weapon'and 'Ammo stock'or e and e.kind=='level'and 'Card level'or e and e.kind=='timer'and 'Timer value'or 'Stock'
  if e then
   local raw=ok and (row.kind=='weapon'and c.h.ammo[e.id+1]or c.inventory[e.id])or nil
   local current=raw~=nil and raw~=0xffff and raw&gt;=0 and ((e.id==23 and row.kind=='gadget'and raw==0)and 'Attached to SOCOM'or tostring(raw&amp;0x7fff))or 'Not owned'
   row.info.Caption='In inventory: '..current..'\r\n'..(e.note or (row.kind=='weapon'and 'Grant at least this stock; capacity is raised when needed.'or e.kind=='consumable'and 'Grant at least this stock; capacity is raised when needed.'or 'Adds this item to inventory.'))
  end
 end
 if not ok then memo.Lines.Text='Waiting for normal gameplay.\r\n'..errorText(c);return end
 local text={P.error and ('Action: '..P.error)or G.status,'',
  'Equipped weapon: '..displayName('weapon',c.activeWeapon),
  'Equipped gadget: '..displayName('gadget',c.activeGadget),
  'Area: '..c.stage..' | Inventory actions are one-shot.',
  'Health/no-alert toggles continue independently.','', 'Weapon inventory:'}
 for _,e in ipairs(G.weapons)do
  local n=c.h.ammo[e.id+1]
  text[#text+1]=string.format('  %-15s %s',e.name,n&lt;0 and 'Not owned'or (n..' / '..c.h.ammoMax[e.id+1]))
 end
 if G.logError then text[#text+1]='Action log: '..errorText(G.logError)end
 memo.Lines.Text=table.concat(text,'\r\n')
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 G.closeLog()
 if not closing then form.OnClose=nil;form.destroy()end
 if SPMInventoryPanel==P then SPMInventoryPanel=nil end
 local record=getAddressList().getMemoryRecordByID(705)
 if record and record.Description:match('^Weapon &amp; gadget selector')and record.Active then record.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=250;timer.OnTimer=P.tick
SPMInventoryPanel=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[Special-Missions/spm-discovery.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Read-only discovery of resident actor lists and relocated overlay parameters.
local D={version=1,root=nil}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xffffffff end
local function offset(p,n)
 assert(p and p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'Invalid PSX pointer')
 return p&amp;0x1fffff
end
local function header(ram,o)
 local b=assert(readBytes(ram+o,32,true),'Actor header unavailable')
 assert(#b==32,'Short actor header')
 local function w(i)return b[i+1]|(b[i+2]&lt;&lt;8)|(b[i+3]&lt;&lt;16)|(b[i+4]&lt;&lt;24)end
 return {offset=o,prev=w(0),next=w(4),act=w(8),die=w(12),namePointer=w(20)}
end
local function rootsValid(ram,root)
 if not root or root&lt;0x10000 or root+9*0x44&gt;0x200000 then return false end
 for i=0,8 do
  local s=header(ram,root+i*0x44);local e=header(ram,root+i*0x44+0x20)
  if s.prev~=0 or s.act~=0 or s.die~=0 or e.next~=0 or e.act~=0 or e.die~=0 then return false end
 end
 return true
end
function D.actorRoot(ram)
 if D.root and rootsValid(ram,D.root)then return D.root end
 local p=offset(u32(ram+0xaca6c),0x100)-0x20
 local seen={}
 for _=1,512 do
  assert(not seen[p],'Actor predecessor cycle');seen[p]=true
  local h=header(ram,p)
  if h.prev==0 then
   local roots={}
   for level=0,8 do local r=p-level*0x44;if rootsValid(ram,r)then roots[#roots+1]=r end end
   assert(#roots==1,'Actor-list root not uniquely identified');D.root=roots[1];return D.root
  end
  p=offset(h.prev,32)
 end
 error('Actor predecessor chain exceeds limit')
end
function D.actors(ram)
 local root=D.actorRoot(ram);local start=root+4*0x44;local finish=start+0x20
 local previous=start;local pointer=u32(ram+start+4);local result={};local seen={}
 for _=1,512 do
  local o=offset(pointer,32)
  if o==finish then
   assert(u32(ram+finish)==0x80000000+previous,'Actor tail changed during enumeration')
   return result
  end
  assert(not seen[o],'Actor-list cycle');seen[o]=true
  local h=header(ram,o)
  assert(h.prev==0x80000000+previous,'Actor list changed while reading')
  if h.act&gt;=0x800c0000 and h.act&lt;0x80200000 and h.die&gt;=0x800c0000 and h.die&lt;0x80200000 then
   local ok,n=pcall(function()return readString(ram+offset(h.namePointer,1),48)end)
   if ok and n then h.name=n;result[#result+1]=h end
  end
  previous=o;pointer=h.next
 end
 error('Actor count exceeds limit')
end
local function binary(ram,start,size)
 local parts={}
 for o=0,size-1,8192 do
  local n=math.min(8192,size-o);local b=assert(readBytes(ram+start+o,n,true),'Overlay read unavailable')
  assert(#b==n,'Short overlay read');parts[#parts+1]=string.char(table.unpack(b))
 end
 return table.concat(parts)
end
function D.overlay(ram)
 local code={start=0xc0000,size=0xa0000}
 code.bytes=binary(ram,code.start,code.size)
 function code.word(o)
  if o&lt;code.start or o+4&gt;code.start+code.size or o%4~=0 then return nil end
  return string.unpack('&lt;I4',code.bytes,o-code.start+1)
 end
 return code
end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function imm(w)local n=w&amp;0xffff;return n&gt;=32768 and n-65536 or n end
local function absolute(code,p,w)
 local base=rs(w)
 for back=1,3 do
  local h=code.word(p-back*4)
  if h and op(h)==15 and rt(h)==base then
   local a=((h&amp;0xffff)&lt;&lt;16)+imm(w)
   if a&gt;=0x800c0000 and a&lt;0x80200000 then return a&amp;0x1fffff end
  end
 end
end
local function guardGateProof(code)
 local found={}
 for p=code.start,code.start+code.size-12,4 do
  local w=code.word(p)
  if (op(w)==36 or op(w)==32)and (w&amp;0xffff)==0xba3 then
   for j=1,2 do
    local a=code.word(p+4*j)
    if a and op(a)==12 and rs(a)==rt(w)then found[a&amp;0xffff]=true end
   end
  end
 end
 return found[1]and found[4]and found[16]
end
function D.reachable(code,entry)
 local pending={entry&amp;0x1fffff};local head=1;local seen={};local words={};local functions=0
 while head&lt;=#pending and functions&lt;180 do
  local fn=pending[head];head=head+1
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;functions=functions+1
   for p=fn,math.min(fn+0x2000,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if op(w)==3 then
     local target=((w&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if target&gt;=0x800c0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1fffff end
    end
    if w==0x3e00008 then words[p+4]=code.word(p+4);break end
   end
  end
 end
 return words
end
-- VR commander uses a materialized struct base, rather than absolute LHs.
function D.guardProfile(ram,actors,code)
 local watchers={}
 for _,a in ipairs(actors)do if a.name=='watcher.c'then watchers[a.offset]=a end end
 if not next(watchers)then return nil,'No standard guards loaded'end
 if not guardGateProof(code)then return nil,'Guard sensing layout not recognized'end
 local function s(n)return n&gt;=32768 and n-65536 or n end
 local function word(p)return code.word(p)end
 local function hi(w)return (w&amp;0xffff)&lt;&lt;16 end
 local matches={}
 for p=code.start,code.start+code.size-0x148,4 do
  local a,b,c,d,e,f,g,h,i,j,k=word(p),word(p+4),word(p+8),word(p+12),word(p+16),word(p+20),word(p+24),word(p+28),word(p+32),word(p+36),word(p+40)
  if a&amp;0xffff0000==0x3c020000 and b&amp;0xffff0000==0x24510000 and c&amp;0xffff0000==0x3c020000 and d==0x86230088 and e&amp;0xffff0000==0x3c040000 and f&amp;0xffff0000==0xac430000 and g==0x8e020014 and h==0x246301f4 and i==0x284200ff and j&amp;0xffff0000==0x14400000 and k&amp;0xffff0000==0xac830000 then
   local command=(hi(a)+s(b&amp;0xffff))&amp;0x1fffff
   local eye=(hi(c)+s(f&amp;0xffff))&amp;0x1fffff
   local shoot=(hi(e)+s(k&amp;0xffff))&amp;0x1fffff
   if command==eye+12 and shoot==eye-4 then
    local configs={}
    for q=p+44,p+0x148-16,4 do
     local load=word(q)
     if load==0x8623008a or load==0x8623008c then
      for z=q+4,q+16,4 do
       local store=word(z)
       if store==f then configs[load&amp;0xffff]=true end
      end
     end
    end
    local vision
    for _,actor in pairs(watchers)do
     for q in pairs(D.reachable(code,actor.act))do
      local w=word(q)
      if w==0x244207d0 and word(q+4)==0x52102a then
       local load=word(q-8);local upper=word(q-12)
       if load and upper and load&amp;0xffff0000==0x8c420000 and upper&amp;0xffff0000==0x3c020000 and ((hi(upper)+s(load&amp;0xffff))&amp;0x1fffff)==eye then vision=q end
      end
     end
    end
    local count,mode=u32(ram+command+8),u32(ram+command+0x18)
    local matched=0
    if configs[0x8a]and configs[0x8c]and vision and count&lt;=8 and mode&lt;=2 then
     for slot=0,7 do
      local ptr=u32(ram+command+0xd4+slot*0x10)
      local actor=ptr&gt;=0x80000000 and ptr&lt;0x80200000 and watchers[ptr&amp;0x1fffff]
      if actor and readBytes(ram+actor.offset+0xb78,1)==slot then matched=matched+1 end
     end
     if matched&gt;0 then
      matches[#matches+1]={command=command,eye=eye,shoot=shoot,ranges=command+0x88,visionPC=vision,matched=matched,
       blocks={{offset=p,bytes=code.bytes:sub(p-code.start+1,p-code.start+0x148)}}}
     end
    end
   end
  end
 end
 if #matches~=1 then return nil,'VR guard commander mapping is not unique ('..#matches..')'end
 return matches[1]
end
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
function D.cameraProfile(actor,code)
 if not cameraNames[actor.name]then return nil end
 local pending={actor.act&amp;0x1fffff};local seen={};local candidates={};local examined=0
 while #pending&gt;0 and examined&lt;100 do
  local fn=table.remove(pending)
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;examined=examined+1
   local words={};local workRegisters={}
   for p=fn,math.min(fn+0x1800,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if p&lt;fn+0x60 and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if (rs(w)==4 and rt(w)==0)or(rs(w)==0 and rt(w)==4)then workRegisters[rd(w)]=true end
    end
    if op(w)==3 then
     local target=((w&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if target&gt;=0x800c0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1fffff end
    end
    if w==0x3e00008 then words[p+4]=code.word(p+4);break end
   end
   for p,w in pairs(words)do
    if op(w)==3 and (((w&amp;0x3ffffff)&lt;&lt;2)|0x80000000)==0x80019ec0 then
     for j=1,7 do
      local compare=words[p+j*4]
      if compare and op(compare)==0 and (compare&amp;63)==42 and rt(compare)==2 then
       local rangeRegister=rs(compare)
       for back=p+j*4-4,math.max(fn,p-0x40),-4 do
        local load=words[back]
        if load and (op(load)==37 or op(load)==35)and rt(load)==rangeRegister and workRegisters[rs(load)]then
         local field=load&amp;0xffff;local size=op(load)==37 and 2 or 4
         if field&gt;=0x100 and field&lt;0x800 then
          local width=false
          for q,z in pairs(words)do if q&lt;p and op(z)==op(load)and rs(z)==rs(load)and (z&amp;0xffff)==field+size then width=true end end
          if width then candidates[field]={range=field,size=size,detector=fn,loadPC=back}end
         end
         break
        end
       end
      end
     end
    end
   end
  end
 end
 local profiles={};for _,v in pairs(candidates)do profiles[#profiles+1]=v end
 if #profiles~=1 then return nil,'Camera distance check is not unique ('..#profiles..')'end
 return profiles[1]
end
function D.guardActors(ram,actors,profile)
 local result={};if not profile then return result end
 local present={};for _,a in ipairs(actors)do present[a.offset]=a end
 for i=0,7 do
  local p=u32(ram+profile.command+0xc8+i*0x10+0xc)
  if p&gt;=0x80000000 and p&lt;0x80200000 then
   local a=present[p&amp;0x1fffff]
   if a and a.name=='watcher.c'and readBytes(ram+a.offset+0xb78,1)==i then a.slot=i;result[a.offset]=a end
  end
 end
 return result
end
return D
]====]):sub(2),
 [ [====[Special-Missions/spm-guard-proximity.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- CE-side proximity modes for standard guards: knockout or kill.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if SPMGuardProximity and SPMGuardProximity.pid==getOpenedProcessID()and SPMGuardProximity.version==5 then return SPMGuardProximity end
if SPMGuardProximity then SPMGuardProximity.stop()end
local A=dofile(dir..'spm-guard-state.lua')
local C={version=5,pid=A.pid,actions=A,enabled=false,mode=nil,radius=A.validateRadius(SPMProximityRadius or 3000),affected=0,batches=0,status='Proximity OFF'}
local ids={knockout=710,kill=711}
local prefixes={knockout='Proximity auto knockout',kill='Proximity auto kill'}
local function record(mode)
 local row=getAddressList().getMemoryRecordByID(ids[mode])
 return row and row.Description:find(prefixes[mode],1,true)==1 and row or nil
end
local function now()return getTickCount()end
function C.setRadius(value)
 C.radius=A.validateRadius(value);SPMProximityRadius=C.radius
 C.status=C.enabled and (C.mode..' ON | radius '..C.radius..' | waiting for nearby guards')or ('Proximity OFF | radius '..C.radius)
 return C.radius
end
function C.disable(mode)
 if mode and C.mode~=mode then return true end
 C.enabled=false;C.mode=nil
 if C.timer then C.timer.Enabled=false end
 C.state=nil;C.nextAction=nil;C.epoch=nil;C.nextCheck=nil
 C.status='Proximity OFF | radius '..C.radius
 for _,kind in ipairs({'knockout','kill'})do local row=record(kind);if row and row.Active then row.Active=false end end
 return true
end
local function audit(result)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/spm-guard-proximity-actions.csv','a+'))
  local success,why=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Proximity action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,mode,radius,slot,actor,distance,hp_before,faint_before\n'))end
   for _,g in ipairs(result.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%d,%d,%08X,%.1f,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),C.pid,result.stage,result.mode,result.radius,g.actor.slot,0x80000000+g.actor.offset,g.distance,g.hp,g.faint)))end end
  end)
  f:close();assert(success,why)
 end)
 if not ok then C.logError=tostring(err)end
end
function C.tick()
 if not C.enabled or C.busy then return end
 if getOpenedProcessID()~=C.pid then C.disable();C.status='Stopped: process changed. Re-enable for the new process.';return end
 local time=now();if C.nextCheck and time&lt;C.nextCheck then return end
 C.busy=true
 local ok,err=pcall(function()
  local c=A.nearby(C.radius);C.state=c
  local epoch=c.ram..':'..c.stage
  if C.epoch~=epoch then C.epoch=epoch;C.nextAction=nil end
  C.status=string.format('%s ON | radius %d | %s | %d nearby, %d ready | %d affected',C.mode,C.radius,c.stage,c.inRange,c.nearEligible,C.affected)
  if c.nearEligible&gt;0 and (not C.nextAction or time&gt;=C.nextAction)then
   local result=A.apply(C.mode,{radius=C.radius})
   C.last=result;C.affected=C.affected+result.affected;C.batches=C.batches+1;C.nextAction=now()+1000
   C.status=string.format('%s ON | radius %d | %s | applied to %d guards (%d total)',C.mode,C.radius,result.stage,result.affected,C.affected)
   audit(result)
  end
 end)
 C.busy=false
 if not ok then
  -- Loading, menus, cutscenes, unsupported layouts or moving targets wait for
  -- a new valid context. No stale actor list is used and no dialog steals focus.
  C.state=nil;C.lastError=tostring(err);C.status='Waiting: '..C.lastError;C.nextCheck=now()+1000
 else C.lastError=nil;C.nextCheck=nil end
end
function C.enable(mode)
 assert(ids[mode],'Unknown proximity mode.')
 assert(not C.stopped and getOpenedProcessID()==C.pid,'Reopen proximity controls for this process.')
 if C.enabled and C.mode==mode then return true end
 C.disable();C.mode=mode;C.enabled=true;C.lastError=nil
 if not C.timer then C.timer=createTimer(nil,false);C.timer.Interval=500;C.timer.OnTimer=C.tick end
 -- Enabling the other AA entry must uncheck this entry without stopping the
 -- replacement mode. disable(mode) above is conditional on the current mode.
 C.status=mode..' ON | radius '..C.radius..' | checking every 500 ms'
 C.timer.Enabled=true
 return true
end
function C.stop()
 C.disable();C.stopped=true
 if C.timer then C.timer.destroy();C.timer=nil end
 if SPMGuardProximity==C then SPMGuardProximity=nil end
 return true
end
SPMGuardProximity=C
return C
]====]):sub(2),
 [ [====[Special-Missions/spm-guard-state.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Optional one-shot outcomes for standard watcher.c guards. No injected calls.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=SPMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'spm-reader.lua')end
local D=dofile(dir..'spm-discovery.lua')
local B=dofile(dir..'spm-ownership.lua')
local A={version=2,pid=R.pid,status='Choose a one-shot guard action.'}
local nativeCache
local function u16(a)return assert(readSmallInteger(a),'Guard short unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Guard word unavailable')&amp;0xffffffff end
local function bytes(a,n)
 local out={};for j=0,n-1,4096 do
  local k=math.min(4096,n-j);local b=assert(readBytes(a+j,k,true),'Guard code unavailable');assert(#b==k)
  out[#out+1]=string.char(table.unpack(b))
 end;return table.concat(out)
end
local function hex(s)return s:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function context()
 assert(getOpenedProcessID()==A.pid,'Attached process changed; reopen the guard panel.')
 local h=R.read();local r=h.ram
 assert(h.health&gt;0 and u32(r+0xac450)==0 and u32(r+0xacab0)~=0 and u32(r+0xac454)==0,'Wait for living, normal gameplay.')
 assert(u32(r+0xac44c)&amp;0xd40c0000==0 and u32(r+0xacac8)&amp;0x20002084==0,'Finish the scene or restricted action first.')
 local control=u32(r+0xaca6c)
 assert(control&gt;=0x80000020 and control&lt;0x801ff000,'Normal Snake is not loaded.')
 local snake=(control&amp;0x1fffff)-0x20
 assert(u32(r+snake+8)==0x8005d6e4 and u32(r+snake+12)==0x8005dd38 and u32(r+0xaca98)==0x80000000+snake+0x9c,'Snake actor differs.')
 assert(u32(r+0xbe758+8)==0x8003b960 and u32(r+0xbe758+12)==0x8003baa4 and u16(r+0xbe758+0x2a)==0,'Close the game menu first.')
 local stage=assert(readString(r+0xb5e00,16))
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Area is not ready.')
 return {ram=r,stage=stage,h=h,snake=snake}
end
local function damageProfile(code)
 local header=hex('E0FFBD271000B0AF218080001800BFAF1400B1AF0009118E0000000006002296')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'VR guard damage handler is missing or ambiguous')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'VR guard damage branches differ')end
 match(0x20,'000000000400423067004010211000003E00229600000000FFFF422400140200031C02000900622C5C004010')
 match(0x54,'80180300211862000000628C000000000800400000000000')
 local upper,lower=code.word(fn+0x4c),code.word(fn+0x50)
 assert(upper&amp;0xffff0000==0x3c020000 and lower&amp;0xffff0000==0x24420000,'VR guard switch layout differs')
 local tablePSX=((upper&amp;0xffff)&lt;&lt;16)+signed(lower&amp;0xffff)
 assert(tablePSX&gt;=0x800c0000 and tablePSX+36&lt;=0x80160000,'VR damage switch outside overlay')
 local t=tablePSX&amp;0x1fffff
 assert(code.word(t)==0x80000000+fn+0xe4 and code.word(t+8)==0x80000000+fn+0x6c,'VR lethal/stun mode routing differs')
 match(0x94,'2A002286000000000700401C9C0004262128000001000224DC0802AE')
 match(0x10c,'26002286000000000700401C9C0004262128000001000224DC0802AE')
 match(0x1a8,'EC0802AEF40800AE700000A6')
 match(0x1c0,'280020A6060020A6')
 return {fn=fn,tableOffset=t,code=code.bytes:sub(start,start+0x1dc-1),switch=code.bytes:sub(t-code.start+1,t-code.start+36)}
end
local function recoveryProfile(code)
 local header=hex('D8FFBD271800B0AF218080002000BFAF1C00B1AF700B028E2188A00020004234')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'Guard knockout recovery handler differs.')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'Guard knockout timer layout differs.')end
 match(0x1cc,'5A0B02A6')
 match(0x1f0,'5A0B0286000000002A1051001200401000000000')
 match(0x204,'0009038E000000002A006284000000000400401C9C000426840B0296000000002A0062A4')
 return {fn=fn,code=code.bytes:sub(start,start+0x25c-1)}
end
function A.inspect(useCache)
 local c=context();local r=c.ram
 local actors=D.actors(r)
 c.guards={};c.eligible=0;c.knockedOut=0;c.dead=0;c.skipped=0;c.total=0
 local identity={};local watchers=0
 for _,a in ipairs(actors)do if a.name=='watcher.c'or a.name=='command.c'then
  identity[#identity+1]=a.name..':'..a.offset..':'..a.act..':'..a.die..':'..bytes(r+(a.act&amp;0x1fffff),32)
  if a.name=='watcher.c'then watchers=watchers+1 end
 end end
 if watchers==0 then nativeCache=nil;c.reason='No standard guards loaded';return c end
 table.sort(identity);local key=r..':'..c.stage..':'..table.concat(identity,'|')
 local cached=useCache and nativeCache and nativeCache.key==key and nativeCache or nil
 if cached and bytes(cached.proof.address,32)~=cached.proof.bytes then cached=nil end
 local code=cached and cached.code or D.overlay(r)
 local profile,why
 if cached then profile=cached.profile else profile,why=D.guardProfile(r,actors,code)end
 if not profile then c.reason=why;return c end
 c.profile=profile;c.damage=cached and cached.damage or damageProfile(code);c.recovery=cached and cached.recovery or recoveryProfile(code);c.ownership={}
 c.profileProof={address=r+profile.visionPC-12,bytes=bytes(r+profile.visionPC-12,32)}
 local families=cached and cached.families or {};local reachable=cached and cached.reachable or {};local retained={};local targets={}
 for _,actor in pairs(D.guardActors(r,actors,profile))do
  local w=actor.offset
  assert(actor.name=='watcher.c'and w~=c.snake and w&gt;=0x10000 and w+0xc4c&lt;=0x200000,'Guard ownership differs.')
  local family=actor.act..':'..actor.die;local e=families[family]
  if not e then e=B.ownership(r,actor);assert(e.targets[0x900],'Guard TARGET pointer lacks native ownership proof.');families[family]=e end
  if not retained[family]then c.ownership[#c.ownership+1]=e;retained[family]=true end
  local ptr=u32(r+w+0x900)
  assert(ptr&gt;=0x800b7558 and ptr&lt;0x800b8758 and (ptr-0x800b7558)%0x48==0,'Guard target pool slot differs.')
  assert(not targets[ptr],'Two guards share a damage target.');targets[ptr]=true
  local t=r+(ptr&amp;0x1fffff);local hp,faint=u16(t+0x26),u16(t+0x2a)
  assert(u16(t+2)==2,'Guard target is not enemy-owned.')
  local g={actor=actor,pointer=ptr,target=t,hp=hp,faint=faint,class=u16(t),flags=u16(t+6),action=u32(r+w+0x8ec),status=u32(r+w+0xb70)}
  c.total=c.total+1
  if hp==0 or hp&gt;=32768 then g.reason='dead';c.dead=c.dead+1
  elseif faint==0 or faint&gt;=32768 then g.reason='knocked out / recovering';c.knockedOut=c.knockedOut+1
  elseif g.class&amp;4==0 or g.flags&amp;6~=0 or u16(t+0x42)~=0 or u16(r+w+0xc2c)~=0 then g.reason='busy / not accepting damage';c.skipped=c.skipped+1
  else
   local accepts=reachable[g.action]
   if accepts==nil then accepts=g.action&gt;=0x800c0000 and g.action&lt;0x80160000 and D.reachable(code,g.action)[c.damage.fn]~=nil;reachable[g.action]=accepts end
   if accepts then g.eligible=true;c.eligible=c.eligible+1
   else g.reason='current action has no verified damage path';c.skipped=c.skipped+1 end
  end
  c.guards[#c.guards+1]=g
 end
 table.sort(c.guards,function(a,b)return a.actor.slot&lt;b.actor.slot end)
 nativeCache={key=key,code=code,profile=profile,damage=c.damage,recovery=c.recovery,proof=c.profileProof,families=families,reachable=reachable}
 return c
end
function A.validateRadius(radius)
 radius=tonumber(radius)
 assert(radius and radius==math.floor(radius)and radius&gt;=100 and radius&lt;=20000,'Radius must be a whole number from 100 to 20000 game units.')
 return radius
end
local function distance(r,snake,actor)
 local squared=0
 for i=0,2 do
  local delta=signed(u16(r+snake+0x20+i*2))-signed(u16(r+actor+0x20+i*2))
  squared=squared+delta*delta
 end
 return math.sqrt(squared)
end
function A.nearby(radius)
 radius=A.validateRadius(radius)
 -- Cached scans only nominate candidates. A.apply always rediscovers native
 -- evidence from current RAM and checks range again before any target write.
 local c=A.inspect(true);c.radius=radius;c.inRange=0;c.nearEligible=0
 for _,g in ipairs(c.guards)do
  g.distance=distance(c.ram,c.snake,g.actor.offset);g.inRange=g.distance&lt;=radius
  if g.inRange then c.inRange=c.inRange+1;if g.eligible then c.nearEligible=c.nearEligible+1 end end
 end
 return c
end
function A.apply(mode,options)
 assert(mode=='kill'or mode=='knockout','Choose kill or knockout.')
 options=options or {};local radius=options.radius and A.validateRadius(options.radius)or nil
 local c=A.inspect()
 if radius then
  c.eligible=0
  for _,g in ipairs(c.guards)do if g.eligible then
   g.distance=distance(c.ram,c.snake,g.actor.offset)
   if g.distance&lt;=radius then c.eligible=c.eligible+1 else g.eligible=false;g.reason='outside proximity radius'end
  end end
 end
 assert(c.eligible&gt;0,'No eligible standard guards. '..(c.reason or 'Already down, busy, outside radius, or unsupported.'))
 local writes,notifications={},{}
 local function plan(a,v,label)
  writes[#writes+1]={address=a,before=u16(a),value=v,label=label}
 end
 for _,g in ipairs(c.guards)do if g.eligible then
  local t=g.target
  plan(t+0x3e,mode=='kill'and 1 or 3,'damage mode')
  if mode=='kill'then plan(t+0x26,0,'vital')else plan(t+0x2a,0,'faint')end
  plan(t+0x28,mode=='kill'and g.hp or 0,'damage amount')
  for _,o in ipairs({0x2c,0x2e,0x30})do plan(t+o,0,'impact force')end
  notifications[#notifications+1]={address=t+6,before=g.flags,value=g.flags|4,label='damage notification'}
 end end
 -- Validate the whole batch before any writes; never reuse a previous area.
 local fresh=context();assert(fresh.ram==c.ram and fresh.stage==c.stage and fresh.snake==c.snake,'Area/player changed; refresh.')
 assert(bytes(c.ram+c.damage.fn,#c.damage.code)==c.damage.code and bytes(c.ram+c.damage.tableOffset,36)==c.damage.switch,'Guard damage code changed.')
 assert(bytes(c.profileProof.address,32)==c.profileProof.bytes,'Guard commander binding changed.')
 for _,block in ipairs(c.profile.blocks or {})do assert(bytes(c.ram+block.offset,#block.bytes)==block.bytes,'VR commander code changed.')end
 for _,e in ipairs(c.ownership)do for _,p in ipairs(e.blocks)do assert(bytes(p.address,#p.bytes)==p.bytes,'Guard native ownership code changed.')end end
 for _,g in ipairs(c.guards)do if g.eligible then
  local a,t=g.actor,g.target;local w=c.ram+a.offset
  assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+20)==a.namePointer and readString(c.ram+(a.namePointer&amp;0x1fffff),48)=='watcher.c','Guard actor changed.')
  assert(u32(c.ram+c.profile.command+0xc8+a.slot*0x10+0xc)==0x80000000+a.offset and readBytes(w+0xb78,1)==a.slot,'Commander no longer owns guard.')
  assert(u32(w+0x900)==g.pointer and u32(w+0x8ec)==g.action,'Guard target/action changed; retry.')
  assert(u16(t)==g.class and u16(t+2)==2 and u16(t+0x26)==g.hp and u16(t+0x2a)==g.faint and u16(t+0x42)==0 and u16(w+0xc2c)==0,'Guard damage state changed; retry.')
  if radius then assert(distance(c.ram,c.snake,a.offset)&lt;=radius,'Guard moved outside the proximity radius; retry.')end
 end end
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do assert(u16(v.address)==v.before,'Guard state changed; retry.')end end
 local count=0
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do
  assert(writeSmallInteger(v.address,v.value),'Guard write failed after '..count..' writes.');count=count+1
 end end
 A.last={mode=mode,pid=A.pid,ram=c.ram,stage=c.stage,affected=c.eligible,skipped=c.total-c.eligible,writes=count,guards=c.guards,recovery=c.recovery,command=c.profile.command,radius=radius}
 A.status=string.format('%s requested for %d guards; %d skipped. Resume gameplay.',mode,c.eligible,c.total-c.eligible)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/spm-guard-state-actions.csv','a+'))
  local success,problem=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Guard action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,action,guard,target,hp_before,faint_before\n'))end
   for _,g in ipairs(c.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%08X,%08X,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),A.pid,c.stage,mode,0x80000000+g.actor.offset,g.pointer,g.hp,g.faint)))end end
  end)
  f:close();assert(success,problem)
 end)
 if not ok then A.logError=tostring(err)end
 SPMGuardState=A;return A.last
end
function A.extendKnockout(result,ticks)
 assert(result==A.last and result.mode=='knockout','A fresh knockout result is required.')
 assert(type(ticks)=='number'and ticks==math.floor(ticks)and ticks&gt;=30 and ticks&lt;=10000,'Invalid recovery delay.')
 if A.extension then A.extension.stop()end
 local T={extended=0,stopped=false,remaining={},writes={}};A.extension=T
 for _,g in ipairs(result.guards)do if g.eligible then T.remaining[#T.remaining+1]=g end end
 local start=getTickCount();local timer=createTimer(nil,false);timer.Interval=100;T.timer=timer
 function T.stop()if not T.stopped then T.stopped=true;timer.Enabled=false;timer.destroy()end end
 function T.tick()
  if T.stopped then return end
  local ok,err=pcall(function()
   local c=context();assert(c.ram==result.ram and c.stage==result.stage,'Area changed; recovery extension cancelled.')
   local r=c.ram;assert(bytes(r+result.recovery.fn,#result.recovery.code)==result.recovery.code,'Recovery code changed.')
   for i=#T.remaining,1,-1 do
    local g=T.remaining[i];local a=g.actor;local w=r+a.offset
    assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+0x900)==g.pointer,'Guard owner changed.')
    assert(u32(r+result.command+0xc8+a.slot*0x10+0xc)==0x80000000+a.offset and readBytes(w+0xb78,1)==a.slot,'Guard commander changed.')
    assert(u16(g.target+2)==2 and u16(g.target+0x26)==g.hp,'Guard health/side changed.')
    local time=u32(w+0x8f4)
    if u32(w+0x8ec)==0x80000000+result.recovery.fn and time&gt;=1 and time&lt;32767-ticks and u16(g.target+0x2a)==0 and u16(g.target+0x42)==0 and u32(w+0xb70)&amp;0x20~=0 then
     local old=u16(w+0xb5a);assert(old&lt;32768,'Recovery threshold differs.')
     local value=math.max(old,time+ticks)
     assert(writeSmallInteger(w+0xb5a,value),'Recovery delay write failed.')
     T.writes[#T.writes+1]={actor=a.offset,before=old,after=value};T.extended=T.extended+1;table.remove(T.remaining,i)
    end
   end
   if #T.remaining==0 then A.status='Extended knockout applied to '..T.extended..' guards; they will recover normally.';T.stop()end
  end)
  if not ok then T.error=tostring(err);A.status='Recovery extension stopped: '..T.error;T.stop()
  elseif getTickCount()-start&gt;=15000 then T.error='Timed out waiting for guards to reach the floor.';A.status=T.error;T.stop()end
 end
 timer.OnTimer=T.tick;timer.Enabled=true
 A.status='Knockout requested; waiting to extend the normal recovery timers.'
 return T
end
SPMGuardState=A
return A
]====]):sub(2),
 [ [====[Special-Missions/spm-inventory.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- One-shot inventory grants and normal game equipment-selection requests.
-- All weapon/item slots are selectable, including equipment not yet owned.
if SPMInventory and SPMInventory.pid==getOpenedProcessID()then return SPMInventory end
if SPMInventory and SPMInventory.closeLog then SPMInventory.closeLog()end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=SPMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'spm-reader.lua')end
local G={pid=R.pid,reader=R,version=1,pending={},status='Choose equipment to add to inventory.'}
G.weapons={
 {id=0,name='SOCOM',stock=25},{id=1,name='FAMAS',stock=100},
 {id=2,name='Grenade',stock=8},{id=3,name='Nikita',stock=10},
 {id=4,name='Stinger',stock=10},{id=5,name='Claymore',stock=8},
 {id=6,name='C4',stock=8},{id=7,name='Stun grenade',stock=8},
 {id=8,name='Chaff grenade',stock=8},{id=9,name='PSG1',stock=10},
}
G.gadgets={
 {id=0,name='Cigarettes'},{id=1,name='Binoculars'},
 {id=2,name='Cardboard box A'},{id=3,name='Cardboard box B'},{id=4,name='Cardboard box C'},
 {id=5,name='Night-vision goggles'},{id=6,name='Thermal goggles'},
 {id=7,name='Gas mask'},{id=8,name='Body armor'},{id=9,name='Ketchup'},
 {id=10,name='Stealth camouflage'},{id=11,name='Bandana'},{id=12,name='Camera'},
 {id=13,name='Rations',kind='consumable',stock=5},
 {id=14,name='Cold medicine',kind='consumable',stock=5},
 {id=15,name='Diazepam',kind='consumable',stock=5},
 {id=16,name='PAL key',note='Adds the PAL key. Its temperature/state stays under game control.'},
 {id=17,name='Key card',kind='level',stock=7,note='Choose an access level from 1 to 7.'},
 {id=18,name='Time bomb (story countdown)',kind='timer',stock=30000,equipable=false,
  note='Story time-bomb value. Adding it can start a countdown; the value uses game timer units.'},
 {id=19,name='Mine detector'},{id=20,name='MO disk'},{id=21,name='Rope'},
 {id=22,name='Handkerchief'},
 {id=23,name='SOCOM suppressor',equipable=false,note='Adds the suppressor. SOCOM attaches it through the normal weapon update.'},
}
local function u16(a)return assert(readSmallInteger(a),'Inventory read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Game state unavailable')&amp;0xffffffff end
local function signed32(v)return v&gt;=0x80000000 and v-0x100000000 or v end
local function owned(raw)return raw~=0xffff end
local function amount(raw)return owned(raw)and (raw&amp;0x7fff)or 0 end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xffff),'Inventory write failed')end
local function fingerprint(a,expected)
 local b=assert(readBytes(a,#expected,true),'Equipment-switch code unavailable')
 for i,v in ipairs(expected)do assert(b[i]==v,'Equipment-switch layout differs')end
end
local function entry(kind,id)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Select valid equipment')
 local list=kind=='weapon'and G.weapons or G.gadgets
 local e=list[id+1];assert(e and e.id==id,'Equipment ID out of range')
 return e
end
function G.context(writing)
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xac450)==0 and u32(ram+0xacab0)~=0,'Wait for area loading to finish.')
 local control=u32(ram+0xaca6c)
 assert(control&gt;=0x80000020 and control&lt;0x80200000,'Snake is not ready.')
 local work=(control&amp;0x1fffff)-0x20
 assert(work+0xa24&lt;0x200000,'Snake actor bounds differ.')
 assert(u32(ram+work+8)==0x8005d6e4 and u32(ram+work+12)==0x8005dd38,'Wait for normal gameplay.')
 assert(u32(ram+0xaca98)==0x80000000+work+0x9c,'Snake body ownership differs.')
 local flags=u32(ram+0xac44c);local player=u32(ram+0xacac8)
 local ready=h.health&gt;0 and u32(ram+0xac454)==0 and flags&amp;0xd40c0000==0 and player&amp;0x20002084==0
 if writing then assert(ready,'Finish the cutscene or restricted action first.')end
 return {h=h,ram=ram,work=work,ready=ready,frame=u32(ram+0xaca60),
  activeWeapon=signed32(u32(ram+work+0x918)),activeGadget=signed32(u32(ram+work+0x9a4)),
  stage=readString(ram+0xb5e00,16)or '?'}
end
local function log(kind,e,requested,actual,equipping,c)
 local ok,err=pcall(function()
  if not G.log then
   G.logPath=dir..'../../logs/spm-inventory-actions-'..G.pid..'.csv'
   G.log=assert(io.open(G.logPath,'a'))
   if G.log:seek()==0 then G.log:write('utc,stage,category,id,name,requested,actual,equip\n')end
  end
  local name='"'..e.name:gsub('"','""')..'"'
  assert(G.log:write(table.concat({os.date('!%Y-%m-%dT%H:%M:%SZ'),c.stage,kind,e.id,name,requested,actual,equipping and 1 or 0},',')..'\n'))
  G.log:flush()
 end)
 if not ok then G.logError=tostring(err)end
end
function G.closeLog()
 if G.log then G.log:close();G.log=nil end
end
function G.equip(kind,id,c)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Equipment ID must be an integer')
 local e=id==-1 and {id=-1,name='Nothing'}or entry(kind,id)
 assert(e.equipable~=false,'Add this item to inventory; it is not directly equipped.')
 c=c or G.context(true)
 R.checkFeature('inventory')
 local address=kind=='weapon'and 0xb5e32 or 0xb5e5a
 if id&gt;=0 then assert(owned(u16(c.ram+address+id*2)),'Add the selected equipment first.')end
 -- These are the same requested slots used by the normal inventory menu.
 -- The game creates/removes equipment actors and updates its active caches.
 local slot=kind=='weapon'and 0xb5e2c or 0xb5e2e
 put16(c.ram+slot,id)
 G.pending[kind]={id=id,name=e.name,ram=c.ram,work=c.work,frame=c.frame}
 G.status=e.name..' selected. Resume gameplay to finish equipping.'
 return true
end
function G.grant(kind,id,quantity,equipping)
 local e=entry(kind,id)
 assert(not equipping or e.equipable~=false,'This item is added to inventory without equipping.')
 quantity=tonumber(quantity or e.stock or 1)
 local maximum=kind=='weapon'and 9999 or e.kind=='level'and 7 or e.kind=='timer'and 32767 or e.kind=='consumable'and 9999 or 1
 assert(quantity and quantity==math.floor(quantity)and quantity&gt;=1 and quantity&lt;=maximum,'Amount must be a whole number from 1 to '..maximum..'.')
 local c=G.context(true)
 R.checkFeature('inventory')
 local base=kind=='weapon'and 0xb5e32 or 0xb5e5a
 local address=c.ram+base+id*2;local raw=u16(address)
 local value=(kind=='weapon'or e.kind)and math.max(amount(raw),quantity)or 1
 assert(value&lt;32768,'Existing inventory count is invalid.')
 local capacity
 if kind=='weapon'then capacity=c.ram+0xb5e46+id*2
 elseif e.kind=='consumable'then capacity=c.ram+0xb5e5a+(id+11)*2 end
 if capacity then
  local old=u16(capacity);if old&gt;=32768 then old=0 end
  if old&lt;value then put16(capacity,value)end
 end
 put16(address,value)
 local actual=u16(address)
 assert(owned(actual),'Game did not retain the inventory entry.')
 G.status=e.name..' added to inventory.'
 if equipping then G.equip(kind,id,c)end
 log(kind,e,quantity,actual,equipping,c)
 return {id=id,name=e.name,value=actual,capacity=capacity and u16(capacity)or nil,equipping=not not equipping}
end
function G.inspect()
 local c=G.context(false);c.inventory={}
 for _,e in ipairs(G.gadgets)do c.inventory[e.id]=u16(c.ram+0xb5e5a+e.id*2)end
 for kind,p in pairs(G.pending)do
  local actual=kind=='weapon'and c.activeWeapon or c.activeGadget
  local requested=kind=='weapon'and c.h.weapon or c.h.item
  if actual==p.id then
   G.status=p.name..' equipped.';G.pending[kind]=nil
  elseif c.ram~=p.ram or c.work~=p.work then
   G.status=p.name..' was added; the area changed before equipment was confirmed.';G.pending[kind]=nil
  elseif c.frame-p.frame&gt;180 and requested~=p.id then
   G.status=p.name..' is in inventory. The game selected different equipment.';G.pending[kind]=nil
  end
 end
 return c
end
G.entry=entry;G.owned=owned;G.amount=amount
SPMInventory=G
return G
]====]):sub(2),
 [ [====[Special-Missions/spm-mission-clear-proofs.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
return {
 {offset=0xD8A18,hex='212880000e80033c020002240b80043ca04e62ac4cc4828c0010033c251043004cc482ac0b01a2900000000002004014010042240b01a2a00800e00300000000'},
 {offset=0xD9524,hex='e8ffbd271000b0af218080001400bfaf0b010392000000000800622c470040100e80023c6845422480180300211862000000628c0000000008004000000000001801028e0000000082100200010042300c0040100b80023c105e44241e008284ffff032402004310000000001e0083a41c0082840000000002004310000000001c0083a4d062030c000000000b80043cc8ca828c0020033c2510430094650308c8ca82ac0b0102920000000001004224a662030c0b0102a298650308000000000b80023c105e44241600828400000000160040180e80023ca04e438c05000224120062100200022420008384000000000300621000000000a662030c000000009e64030c2120000294650308000000000b80023c305e4384020002240300621000000000a662030c000000000b01029200000000010042240b0102a21400bf8f1000b08f0800e0031800bd27'},
 {offset=0xD9A18,hex='d0ffbd272000b0af21808000c800042421288000213080002800bfaf82ef000c2400b1af1801028e0000000001004230e80040140e80113c'},
 {offset=0xDA114,hex='265e4284000000000500401c000000001801028e0000000002004234180102ae1801028e0000000042100200010042300b00401400000000d265030c212000024965030c212000021801028e0000000042100200010042300300401000000000b365030c212000024564030c212000022800bf8f2400b18f2000b08f0800e0033000bd27'},
 {offset=0xD9990,hex='4467000ca4458424080002160e80043ca04e828e0000000004005314000000008662030c212020020e80043c'},
 {offset=0xDD5D8,hex='c8ffbd272000b2af219080003000bfaf2c00b5af2800b4af2400b3af1c00b1af1800b0af2800448e7c65000c1000a527218840001400201aafed15340e80143c010013241000a38f0000000004006294000000000d005510afed0234040070944467000c284884260200021600000000ae0353a21000a28fffff312614004224f0ff201e1000a2af211000003000bf8f2c00b58f2800b48f2400b38f2000b28f1c00b18f1800b08f0800e0033800bd27'},
 {offset=0xDE10C,hex='e8ffbd271000b0af218080001400bfafae0303920100022412006210020062280500401000000000080060100000000071780308000000000200022410006210000000007178030800000000ab71030c212000027675030c2120000271780308000000000777030c21200002ae030292000000000100422471780308ae0302a22776030c21200002b403038e00000000090060100c00022406006214010062240b80033c8100022450c462ac71780308b40300aeb40302ae1400bf8f1000b08f0800e0031800bd270800e00300000000'},
 {offset=0xD9278,hex='c0ffbd273800b0af218080000e80023c3c00bfaf5c454c24030089890000899907008a8904008a9908008b812b00a9ab2800a9bb2f00aaab2c00aabb3000aba309008981000000003100a9a30b80023c6cca438c40000296000000004e0062a40b80023c105e432422006284340007860b0041042130000021206000220003240b00c2280600401002006324211064000000428400000000f9ff40040100c6240a0103920500022408006214040002240e80033c884e628c0000000010004234884e62ac0a01039204000224070062140a00c2280e80023c884e438cefff042424186400e9640308884e43ac0f0040100b80033c105e63241100c22440100200211043002120a603000043842800829000000000180062001401028e121800002338e30021104300140102ae0a01039202000224120062140e80023c804e438c000000000600601000000000010002240700621000000000fe640308000000001401028eb5ffe724fd6403084b0042241401028ee7ffe72419004224140102ae0200e1040e80023c21380000984e428c000000000200410400000000231002002a10e20003004014020006241e650308030006241200c0100e80033c904e632480200600ffffc62480100600211043000000458c21208300000085ac0000428c000000000200410400000000231002002a10e200efff4014000000000100c6240300c22c050040100e80033c904e63248010060021104300000047ac040002241000a2a71800a2270e80043c904e83240e80053c1400a2af34000886884ea28c403006000c0067ac904e848c0400678c0800638c25104600884ea2ac1800a8af1c00a4af2000a7af2400a3af1801028e3800038e0800423406006010180102ae9662030c000000003800048e878c000c1000a527380000ae080100a23c00bf8f3800b08f0800e0034000bd27'},
 {offset=0x23170,hex='212880000b80043c904c838ce8ffbd271000bfaf0000628c000000000f00401000000000904c842400006294000000000500451400000000020063940400828c778c000821104300040063240000628c00000000f4ff4014000000000180043ca632020c44028424211000001000bf8f000000000800e0031800bd27'},
 {offset=0x2321C,hex='e8ffbd270b80023c50c4428c211880001000b0af2180a000070040141400bfaf0b80023cc8ca428c000000000020423007004010000000000180043c58028424a632020c21286000a08c0008211000005c8c000c2120600003004424028d000c212800021400bf8f1000b08f0800e0031800bd27'}
}
]====]):sub(2),
 [ [====[Special-Missions/spm-mission-clear.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- One-shot normal mission clear for verified European Special Missions native layouts.
-- No code patch, injected call, timer/score edit or direct completion-table write.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local root=dir
local G=dofile(root..'spm-inventory.lua')
local proofs=dofile(dir..'spm-mission-clear-proofs.lua')
local M={pid=G.pid,version=2}
local function u32(a)return assert(readInteger(a),'Clear state unavailable')&amp;0xffffffff end
local function byte(a)return assert(readBytes(a,1),'Clear byte unavailable')end
local function procedure(r,id)
 assert(id&gt;0 and id&lt;=0xffff,'Invalid live clear procedure ID')
 -- Mirror the native GCL procedure lookup at 80023078, without executing it.
 local tablePSX,basePSX=u32(r+0xb4c90),u32(r+0xb4c94)
 assert(tablePSX&gt;=0x80010000 and tablePSX&lt;0x801ffff8 and tablePSX%4==0,'Script procedure table invalid')
 assert(basePSX&gt;tablePSX and basePSX&lt;0x80200000,'Script procedure base invalid')
 local t,b=tablePSX&amp;0x1fffff,basePSX&amp;0x1fffff
 local found,ended
 for i=0,1023 do
  assert(t+i*4+4&lt;=0x200000,'Script table exceeds guest RAM')
  local entry=u32(r+t+i*4)
  if entry==0 then
   assert(b==t+(i+1)*4,'Script table/base binding differs');ended=true;break
  end
  if entry&amp;0xffff==id then assert(not found,'Ambiguous clear procedure');found=b+(entry&gt;&gt;16)end
 end
 assert(ended and found and found+3&lt;0x200000,'Live clear procedure not found')
 assert(byte(r+found)==0x40,'Clear procedure header differs')
 local size=byte(r+found+1)*256+byte(r+found+2)
 assert(size&gt;=3 and found+size&lt;=0x200000,'Clear procedure length invalid')
 local body={};for _,v in ipairs(assert(readBytes(r+found,size,true)))do body[#body+1]=string.char(v)end
 assert(#body==size,'Short clear procedure read')
 return found,table.concat(body)
end
local function code(r)
 for _,p in ipairs(proofs)do
  local expected={};for v in p.hex:gmatch('%x%x')do expected[#expected+1]=tonumber(v,16)end
  local actual=assert(readBytes(r+p.offset,#expected,true),'Clear code unavailable')
  assert(#actual==#expected,'Short clear code read')
  for i,v in ipairs(expected)do assert(actual[i]==v,'Mission-clear native code differs')end
 end
end
local function actor(r,level,name,act,die)
 local start=0xadc90+level*0x44;local finish=start+0x20
 local previous=start;local p=u32(r+start+4);local seen={};local found
 for _=1,256 do
  assert(p&gt;=0x80010000 and p&lt;=0x801ffc00,'Actor bounds differ')
  local o=p&amp;0x1fffff
  assert(u32(r+o)==0x80000000+previous,'Actor list changed')
  if o==finish then assert(found,'Mission actor missing: '..name);return found end
  assert(not seen[o],'Actor list cycle');seen[o]=true
  if u32(r+o+8)==act and u32(r+o+12)==die then
   local n=u32(r+o+20);assert(n&gt;=0x80010000 and n&lt;0x80200000,'Actor name invalid')
   if readString(r+(n&amp;0x1fffff),48)==name then assert(not found,'Ambiguous mission actor');found=o end
  end
  previous=o;p=u32(r+o+4)
 end
 error('Actor traversal exceeded bound')
end
function M.inspect()
 assert(getOpenedProcessID()==M.pid,'Attached process changed')
 local c=G.context(true);local r=c.ram
 assert(c.stage:match('^vr_[%w_]+$'),'Enter a playable VR mission')
 assert((readSmallInteger(r+0xbe758+0x2a)&amp;0xffff)==0,'Close the game menu')
 code(r)
 c.vr=actor(r,5,'vr.c',0x800d9a18,0x800da198)
 c.results=actor(r,7,'vrclear.c',0x800de10c,0x800de1d4)
 c.mode=u32(r+0xe4ea0);c.sequence=byte(r+c.vr+0x10b)
 c.resultPhase=byte(r+c.results+0x3ae)
 c.flags=u32(r+0xac44c)
 assert(c.mode==1 and c.sequence==0 and c.resultPhase==0,'Mission is already clearing or not playing')
 assert(c.flags&amp;0x10000000==0,'Mission already frozen')
 -- GCL_ExecProc receives a script procedure ID here, not a RAM pointer.
 assert(byte(r+c.vr+0x108)==1,'Normal clear script unavailable')
 c.procedure=u32(r+c.vr+0x38)
 c.script,c.scriptBytes=procedure(r,c.procedure)
 return c
end
function M.apply()
 local c=M.inspect();local fresh=M.inspect()
 assert(fresh.ram==c.ram and fresh.stage==c.stage and fresh.work==c.work and fresh.vr==c.vr and fresh.results==c.results and fresh.flags==c.flags and fresh.procedure==c.procedure and fresh.script==c.script and fresh.scriptBytes==c.scriptBytes,'Mission changed; retry')
 -- Exactly the three state changes performed by the native clear handler D87B8.
 -- Set the sequence last: subsequent game updates perform clear presentation,
 -- script callbacks, completion bookkeeping and results through normal code.
 assert(writeInteger(c.ram+0xac44c,c.flags|0x10000000),'Could not freeze clear transition')
 assert(writeInteger(c.ram+0xe4ea0,2),'Could not set normal clear mode')
 assert(writeBytes(c.ram+c.vr+0x10b,1),'Could not start normal clear sequence')
 M.last={pid=M.pid,stage=c.stage,ram=c.ram,vr=c.vr,results=c.results,flagsBefore=c.flags,procedure=c.procedure,script=c.script}
 SPMMissionClear=M
 return string.format('Normal clear requested in %s; VR actor=%08X results=%08X. Current timer and game result calculation retained.',c.stage,0x80000000+c.vr,0x80000000+c.results)
end
return M
]====]):sub(2),
 [ [====[Special-Missions/spm-no-alert.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Data-only guard/camera suppression. Profiles are resolved from live MIPS code.
if SPMNoAlert then
 assert(SPMNoAlert.version==2 and SPMNoAlert.pid==getOpenedProcessID(),'Stop the previous no-alert controller before upgrading')
 return SPMNoAlert
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=SPMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'spm-reader.lua')end
local D=dofile(dir..'spm-discovery.lua')
local A={pid=R.pid,reader=R,discovery=D,version=2,enabled=false,wanted=false,status='OFF',rebinds=0,cache={}}
local MASK=0x17
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
local function u16(a)return assert(readSmallInteger(a),'Short read unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Word read unavailable')&amp;0xffffffff end
local function byte(a)return assert(readBytes(a,1),'Byte read unavailable')end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xffff),'Short write failed')end
local function put32(a,v)assert(writeInteger(a,v&amp;0xffffffff),'Word write failed')end
local function put8(a,v)assert(writeBytes(a,v&amp;255),'Byte write failed')end
local function stamp(ram,p,n)
 local b=assert(readBytes(ram+p,n or 16,true),'Code fingerprint unavailable')
 return string.char(table.unpack(b))
end
local function blocksValid(r,p)
 for _,b in ipairs(p.blocks or {})do if stamp(r,b.offset,#b.bytes)~=b.bytes then return false end end
 return true
end
local function family(a)return a.name..':'..a.act..':'..a.die end
local function actorSame(a,b)return a and b and a.offset==b.offset and a.act==b.act and a.die==b.die and a.name==b.name end
local function now()return getTickCount and getTickCount()or math.floor(os.clock()*1000)end
function A.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xac450)==0 and u32(ram+0xacab0)~=0,'Area loading')
 local stage=assert(readString(ram+0xb5e00,16),'Stage unavailable')
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Stage not ready')
 local actors=D.actors(ram);local present={};local families={};local samples={}
 for _,a in ipairs(actors)do
  present[a.offset]=a
  if a.name=='watcher.c'or cameraNames[a.name]or a.name=='command.c'then
   local key=family(a)
   if not families[key]then families[key]=true;samples[#samples+1]=key..stamp(ram,a.act&amp;0x1fffff,32)end
  end
 end
 table.sort(samples)
 local epoch=tostring(ram)..':'..stage
 local key=epoch..':'..table.concat(samples,'|')
 local profile=A.cache[key]
 if profile then
  if profile.guard and not blocksValid(ram,profile.guard)then profile=nil end
  if profile and profile.guard and stamp(ram,profile.guard.proofPC,32)~=profile.guard.proof then profile=nil end
  if profile then for _,p in pairs(profile.cameras)do if stamp(ram,p.loadPC,16)~=p.proof then profile=nil;break end end end
 end
 if not profile or (profile.unsupported&gt;0 and now()-(profile.time or 0)&gt;1000)then
  local code=D.overlay(ram)
  profile={cameras={},unsupported=0,time=now()}
  local p,why=D.guardProfile(ram,actors,code);profile.guard=p;profile.guardReason=why
  local checked={}
  for _,a in ipairs(actors)do
   if a.name=='watcher.c'and not p then profile.unsupported=profile.unsupported+1 end
   if cameraNames[a.name]and not checked[family(a)]then
    checked[family(a)]=true
    local cp,err=D.cameraProfile(a,code)
    if cp then cp.proof=stamp(ram,cp.loadPC,16);profile.cameras[family(a)]=cp
    else profile.unsupported=profile.unsupported+1;profile.cameraReason=err end
   end
  end
  if p then p.proofPC=p.visionPC-12;p.proof=stamp(ram,p.proofPC,32)end
  A.cache[key]=profile
 end
 local c={ram=ram,stage=stage,epoch=epoch,key=key,h=h,actors=present,profile=profile,guards=D.guardActors(ram,actors,profile.guard),cameras={}}
 for _,a in ipairs(actors)do
  local cp=profile.cameras[family(a)]
  if cp then a.cameraProfile=cp;c.cameras[a.offset]=a end
 end
 return c
end
local function fresh(c)
 -- Stage/DRAM changes unload the previous area. Never restore through its old
 -- addresses into a replacement overlay or replacement actor allocation.
 if not A.snapshot or A.snapshot.epoch~=c.epoch then
  A.snapshot={epoch=c.epoch,ram=c.ram,stage=c.stage,guards={},cameras={}}
  A.rebinds=A.rebinds+1
 end
 local s=A.snapshot;local p=c.profile.guard
 if p then
  if not s.guard or s.guard.profile.command~=p.command or s.guard.profile.proof~=p.proof then
   s.guard={profile=p,ranges={}}
  end
  for i=0,2 do
   local v=u16(c.ram+p.ranges+i*2)
   if v~=0x8000 then assert(v&lt;32768,'Existing negative guard range');s.guard.ranges[i+1]=v end
   assert(s.guard.ranges[i+1]~=nil,'Guard ranges already modified without ownership')
  end
 end
 return s
end
local function apply(c)
 local s=fresh(c);local ng,nc=0,0
 if c.profile.guard then
  local p=c.profile.guard
  for i=0,2 do if u16(c.ram+p.ranges+i*2)~=0x8000 then put16(c.ram+p.ranges+i*2,0x8000)end end
  if u32(c.ram+p.eye)~=0xffff8000 then put32(c.ram+p.eye,0xffff8000)end
  for o,g in pairs(c.guards)do
   ng=ng+1;local flags=byte(c.ram+o+0xba3);local saved=s.guards[o]
   if not saved or not actorSame(saved.actor,g)or saved.actor.slot~=g.slot then saved={actor=g,mask=flags&amp;MASK};s.guards[o]=saved end
   saved.mask=saved.mask|(flags&amp;MASK)
   if flags&amp;MASK~=0 then put8(c.ram+o+0xba3,flags&amp;(~MASK&amp;255))end
   for _,field in ipairs({0xb92,0xb94})do if u16(c.ram+o+field)~=0 then put16(c.ram+o+field,0)end end
   if u32(c.ram+o+0xb98)~=0 then put32(c.ram+o+0xb98,0)end
   for _,field in ipairs({0xba1,0xba2})do if byte(c.ram+o+field)~=0 then put8(c.ram+o+field,0)end end
  end
 end
 for o,camera in pairs(c.cameras)do
  nc=nc+1;local cp=camera.cameraProfile
  local v=cp.size==4 and u32(c.ram+o+cp.range)or u16(c.ram+o+cp.range);local old=s.cameras[o]
  if not old or not actorSame(old.actor,camera)or old.field~=cp.range or old.size~=cp.size or old.proof~=cp.proof then
   old={actor=camera,field=cp.range,size=cp.size,range=v,proof=cp.proof,pc=cp.loadPC};s.cameras[o]=old
  elseif v~=0 then old.range=v end -- reinitialized/replaced camera parameters
  if v~=0 then if cp.size==4 then put32(c.ram+o+cp.range,0)else put16(c.ram+o+cp.range,0)end end
 end
 A.guardCount=ng;A.cameraCount=nc;A.stage=c.stage;A.profile=c.profile
 A.status=string.format('ON | %s | %d guards, %d cameras | area binds %d',c.stage,ng,nc,A.rebinds)
 if c.profile.unsupported&gt;0 then A.status=A.status..' | PARTIAL: unrecognized sensing layout'end
end
local function restore()
 if not A.snapshot then return end
 assert(getOpenedProcessID()==A.pid,'Original process required for cleanup')
 local c=A.context();local s=A.snapshot
 if c.epoch~=s.epoch then A.snapshot=nil;return end
 local p=s.guard and s.guard.profile
 if p and blocksValid(c.ram,p)and stamp(c.ram,p.proofPC,32)==p.proof then
  for i,v in ipairs(s.guard.ranges)do put16(c.ram+p.ranges+(i-1)*2,v)end
  local mode=u32(c.ram+p.command+0x18)
  if mode&lt;=2 then local r=s.guard.ranges[mode+1];put32(c.ram+p.eye,r);put32(c.ram+p.shoot,r+500)end
 end
 for o,old in pairs(s.guards)do
  local g=c.actors[o]
  if actorSame(g,old.actor)and byte(c.ram+o+0xb78)==old.actor.slot then
   put8(c.ram+o+0xba3,(byte(c.ram+o+0xba3)&amp;(~MASK&amp;255))|old.mask)
  end
 end
 for o,old in pairs(s.cameras)do
  if actorSame(c.actors[o],old.actor)and stamp(c.ram,old.pc,16)==old.proof then
   if old.size==4 then put32(c.ram+o+old.field,old.range)else put16(c.ram+o+old.field,old.range)end
  end
 end
 A.snapshot=nil
end
function A.disable()
 A.wanted=false;A.enabled=false
 local ok,err=pcall(restore)
 if not ok then A.status='CLEANUP WAITING: '..tostring(err);return false,A.status end
 A.status='OFF';return true
end
function A.enable()
 assert(not A.stopped,'Reload the stopped no-alert controller')
 if A.wanted then return true end
 assert(not A.snapshot,'Finish pending cleanup before enabling')
 local c=A.context()
 A.wanted=true;A.enabled=true
 local ok,err=pcall(apply,c)
 if not ok then A.disable();error(err)end
 return true
end
function A.tick()
 if A.stopped then return end
 if not A.wanted then if A.snapshot then A.disable()end;return end
 if getOpenedProcessID()~=A.pid then A.enabled=false;A.status='WAITING: original process required';return end
 local ok,err=pcall(function()apply(A.context())end)
 if ok then A.enabled=true else A.enabled=false;A.status='WAITING FOR AREA: '..tostring(err)end
end
function A.stop()
 local ok,err=A.disable();if not ok then return false,err end
 A.stopped=true;A.timer.Enabled=false;A.timer.destroy();A.timer=nil
 if SPMNoAlert==A then SPMNoAlert=nil end
 return true
end
A.timer=createTimer(nil,false);A.timer.Interval=50;A.timer.OnTimer=A.tick;A.timer.Enabled=true
SPMNoAlert=A
return A
]====]):sub(2),
 [ [====[Special-Missions/spm-ownership.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
local B={}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xffffffff end
local function psx(p,n)assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'PSX pointer invalid');return p&amp;0x1fffff end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function binary(r,o,n)
 assert(o&gt;=0 and n&gt;=0 and o+n&lt;=0x200000,'Capture outside RAM')
 local out={}
 for j=0,n-1,4096 do local k=math.min(4096,n-j);local t=assert(readBytes(r+o+j,k,true));assert(#t==k);out[#out+1]=string.char(table.unpack(t))end
 return table.concat(out)
end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function isBranch(w)return op(w)==1 or (op(w)&gt;=4 and op(w)&lt;=7)or op(w)==2 or op(w)==3 or (op(w)==0 and ((w&amp;63)==8 or (w&amp;63)==9))end
local function copy(t)local r={};for k,v in pairs(t)do r[k]=v end;return r end
local function destination(w)
 if op(w)==0 then return rd(w)end
 if (op(w)&gt;=8 and op(w)&lt;=15)or (op(w)&gt;=32 and op(w)&lt;=39)then return rt(w)end
end
-- Conservative backwards slice: only a direct work-field load, a move and/or
-- a left shift are accepted. Branches, calls and complex arithmetic reject it.
local function expression(words,aliases,at,reg,depth)
 if (depth or 0)&gt;5 then return nil end
 if reg==0 then return {kind='constant',value=0}end
 for i=at,math.max(1,at-24),-1 do
  local w=words[i];if isBranch(w)then return nil end
  if destination(w)==reg then
   if op(w)==35 then
    local base=aliases[i][rs(w)]
    if base~=nil and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     local offset=base+signed(w&amp;0xffff)
     if offset&gt;=0x20 and offset&lt;=0x4000 and offset%4==0 then return {kind='field',offset=offset,scale=1}end
    end
   elseif op(w)==9 and rs(w)==0 then return {kind='constant',value=signed(w&amp;0xffff)}
   elseif op(w)==13 and rs(w)==0 then return {kind='constant',value=w&amp;0xffff}
   elseif op(w)==0 then
    local f=w&amp;63
    if (f==33 or f==37)and (rs(w)==0 or rt(w)==0)then
     return expression(words,aliases,i-1,rs(w)==0 and rt(w)or rs(w),(depth or 0)+1)
    elseif f==0 and rs(w)==0 then
     local e=expression(words,aliases,i-1,rt(w),(depth or 0)+1);local shift=(w&gt;&gt;6)&amp;31
     if e and shift&lt;=4 then if e.kind=='field'then e.scale=e.scale*(1&lt;&lt;shift)else e.value=e.value*(1&lt;&lt;shift)end;return e end
    end
   end
   return nil
  end
 end
end
function B.ownership(r,actor)
 assert(binary(r,0x306ec,48)==string.char(124,7,132,143,0,0,0,0,64,0,130,40,3,0,64,20,192,24,4,0,8,0,224,3,33,16,0,0,33,24,100,0,192,24,3,0,11,128,2,60,88,117,66,36,33,24,98,0),'Special Missions TARGET native code differs')
 assert(binary(r,0x3078c,16)==string.char(17,0,128,16,11,128,3,60,124,7,133,143,16,117,99,36),'Special Missions TARGET native code differs')
 local e={targets={},fields={},proofs={},functions=0,blocks={}}
 local overlay=binary(r,0xc0000,0xa0000)
 local queue={{fn=actor.die,base=0},{fn=actor.act,base=0}};local seen={}
 local function mark(field,kind,pc,w)
  if field&lt;0x20 or field&gt;0x4000 then return end
  local v=e.fields[field]or {};e.fields[field]=v;v[kind]={pc=pc,word=w}
 end
 while #queue&gt;0 and e.functions&lt;128 do
  local item=table.remove(queue,1);local fn,base=item.fn,item.base;local key=tostring(fn)..':'..tostring(base)
  if item.aliases then for reg=1,31 do if item.aliases[reg]~=nil then key=key..':'..reg..'='..item.aliases[reg]end end end
  if not seen[key]and fn&gt;=0x800c0000 and fn&lt;0x80160000 and fn%4==0 then
   seen[key]=true;e.functions=e.functions+1
   local offset=(fn&amp;0x1fffff)-0xc0000
   local code=overlay:sub(offset+1,offset+0x1000);local words,aliases={},{};local alias=item.aliases or {[4]=base};local loaded={};local stop=false
   for i=1,#code//4 do
    local w=string.unpack('&lt;I4',code,(i-1)*4+1);local pc=fn+(i-1)*4;words[i]=w;aliases[i]=copy(alias)
    local o=op(w);local field=alias[rs(w)]and alias[rs(w)]+signed(w&amp;0xffff)
    if field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     if o==35 then mark(field,'read',pc,w);loaded[rt(w)]={field=field}
     elseif o==43 then mark(field,'write',pc,w);if loaded[rt(w)]and loaded[rt(w)].field==field and loaded[rt(w)].decrement then mark(field,'decrement',pc,w)end end
    end
    if o==35 and not(field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23)))then loaded[rt(w)]=nil end
    local dest=destination(w);local value
    if o==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if rt(w)==0 then value=alias[rs(w)]elseif rs(w)==0 then value=alias[rt(w)]end
    elseif o==9 and alias[rs(w)]~=nil then value=alias[rs(w)]+signed(w&amp;0xffff)end
    if o==9 and rt(w)==rs(w)and signed(w&amp;0xffff)==-1 and loaded[rt(w)]then loaded[rt(w)].decrement=true
    elseif dest and dest~=0 and o~=35 then loaded[dest]=nil end
    if dest and dest~=0 then alias[dest]=value end
    local prior=words[i-1]
    if prior and (op(prior)==3 or op(prior)==2)then
     local callee=((prior&amp;0x3ffffff)&lt;&lt;2)|0x80000000
     if callee==0x8003078c then
      local exp
      if destination(w)==4 then
       exp=expression({w},{aliases[i]},1,4)
       if not exp and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)and (rs(w)==0 or rt(w)==0)then exp=expression(words,aliases,i-2,rs(w)==0 and rt(w)or rs(w))end
      else exp=expression(words,aliases,i-2,4)end
      if exp and exp.kind=='field'and exp.scale==1 then e.targets[exp.offset]={field=exp.offset,pc=pc-4,word=prior}end
     elseif callee&gt;=0x800c0000 and callee&lt;0x80160000 then
      if op(prior)==2 then
       -- Follow a real unconditional control-flow edge, preserving its work
       -- aliases. Do not fall through into the next unrelated function.
       queue[#queue+1]={fn=callee,aliases=copy(alias)}
      elseif alias[4]and alias[4]&gt;=0 and alias[4]&lt;0x4000 then queue[#queue+1]={fn=callee,base=alias[4]}end
     end
     for j=2,15 do alias[j]=nil;loaded[j]=nil end;alias[24]=nil;alias[25]=nil
    end
    if stop then break end
    if o==2 or (o==0 and (w&amp;63)==8 and rs(w)==31)then stop=true end
   end
   e.blocks[#e.blocks+1]={address=r+(fn&amp;0x1fffff),bytes=code:sub(1,#words*4)}
  end
 end
 return e
end

return B
]====]):sub(2),
 [ [====[Special-Missions/spm-reader.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- European Master Collection Special Missions (SLES_021.36), host build 20872173.
-- All target access in this module is read-only.
assert(process=='METAL GEAR SOLID.exe','Attach to METAL GEAR SOLID.exe')
assert(getModuleSize(process)==30007296,'Unsupported executable image size')
local base,pid=getAddress(process),getOpenedProcessID()
local R={pid=pid,module=base,vtable=base+0xab8cf0,version=1,variant='Special Missions EUR'}
local function bytes(a,n)
 local b=assert(readBytes(a,n,true),'Memory unavailable')
 assert(#b==n,'Incomplete memory read');return b
end
local function fp(a,hex)
 local expected=hex:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)
 local b=bytes(a,#expected)
 assert(string.char(table.unpack(b))==expected,'Special Missions code/layout differs at '..string.format('%X',a))
end
fp(base+0x10b43d,'488D05ACD89A00')
fp(base+0x10b447,'41B900400800')
local function validate(ram)
 assert(ram and ram&gt;0x10000,'Emulated RAM missing')
 assert(readString(ram+0x10000,11)=='SLES_021.36','Only European Special Missions SLES_021.36 is supported')
 -- Actual health load, three-way health synchronization, and alert globals.
 fp(ram+0x51688,'0B80023C265E4284')
 fp(ram+0x52a78,'105E47249808258E1600E2842600A384')
 fp(ram+0x52b80,'212020029808828C0001053C260046A40B80023C1E0A86A4265E46A4')
 fp(ram+0x31c20,'0B80043C78CA848C')
 fp(ram+0x31d04,'0B80033C90CA638C')
end
function R.checkFeature(kind)
 local r=R.ram;validate(r)
 if kind=='health'then
  fp(r+0x52558,'8345010C8000043C9808038E200A11A2000062940000000069FF4230000062A4')
  fp(r+0x5160c,'0B80023CC8CA428C00000000251044000B80013CC8CA22AC0800E00300000000')
  fp(r+0x525b0,'9808038E0000000000006294000000009E004234000062A4')
 elseif kind=='ammo'then
  fp(r+0x668c4,'0B80023C325E43940C0004240B80013C64CA30A40B80013CA4CA24A4FFFF6324325E43A4')
 elseif kind=='inventory'then
  fp(r+0x54570,'0B80023C105E52241C00428604008012180902AE')
  fp(r+0x548e8,'0B80023C105E52241E0042860400A012A40922AE')
 else error('Unsupported VR feature')end
end
local pattern={}
for i=0,7 do pattern[#pattern+1]=string.format('%02X',(R.vtable&gt;&gt;(i*8))&amp;255)end
local found=AOBScan(table.concat(pattern,' '),'+W-C',fsmAligned,'8')
local candidates={}
if found then
 for i=0,found.Count-1 do
  local owner=tonumber(found[i],16);local ram=readQword(owner+0x28)
  if pcall(validate,ram)then candidates[#candidates+1]={owner=owner,ram=ram}end
 end
 found.destroy()
end
assert(#candidates==1,'Expected one validated Special Missions RAM owner; found '..#candidates)
R.owner,R.ram=candidates[1].owner,candidates[1].ram
local function u16(b,o)return b[o+1]|(b[o+2]&lt;&lt;8)end
local function s16(b,o)local n=u16(b,o);return n&gt;=32768 and n-65536 or n end
local function u32(b,o)return u16(b,o)|(u16(b,o+2)&lt;&lt;16)end
R.weapons={'SOCOM','FAMAS','Grenade','Nikita','Stinger','Claymore','C4','Stun grenade','Chaff grenade','PSG1'}
R.modes={[0]='NORMAL',[1]='JAMMING',[2]='EVASION',[3]='ALERT'}
function R.read()
 assert(getOpenedProcessID()==pid and process=='METAL GEAR SOLID.exe','Process changed; reload VR controls')
 assert(readQword(R.owner)==R.vtable,'Emulator owner changed')
 local ram=readQword(R.owner+0x28)
 -- Game selection can replace the guest inside the SAME allocation.
 validate(ram);R.ram=ram
 local stage=readString(ram+0xb5e00,16)
 assert(stage and stage:match('^vr_[%w_]+$')and #stage&lt;=12,'Enter a VR mission')
 local q,g=bytes(ram+0xb5e10,192),bytes(ram+0xaca60,0x50)
 local h={pid=pid,ram=ram,stage=stage,health=s16(q,0x16),maximum=s16(q,0x18),
  weapon=s16(q,0x1c),item=s16(q,0x1e),magazine=s16(g,4),magazineMax=s16(g,0x44),
  alertMode=u32(g,0x18),alertLevel=u32(g,0x30),ration=s16(q,0x64),rationMax=s16(q,0x7a),ammo={},ammoMax={}}
 assert(h.maximum&gt;=1 and h.maximum&lt;=2000 and h.health&gt;=0 and h.health&lt;=h.maximum,'Health layout invalid')
 assert(h.weapon&gt;=-1 and h.weapon&lt;=9 and h.item&gt;=-1 and h.item&lt;=23,'Equipment layout invalid')
 assert(R.modes[h.alertMode]and h.alertLevel&lt;=65535,'Alert layout invalid')
 for i=1,10 do h.ammo[i]=s16(q,0x22+(i-1)*2);h.ammoMax[i]=s16(q,0x36+(i-1)*2)end
 h.weaponName=h.weapon==-1 and 'None'or R.weapons[h.weapon+1]
 h.ammoSelected=h.weapon&gt;=0 and h.ammo[h.weapon+1]or nil
 h.ammoSelectedMax=h.weapon&gt;=0 and h.ammoMax[h.weapon+1]or nil
 h.alertName=R.modes[h.alertMode]
 return h
end
SPMReader=R
return R
]====]):sub(2),
 [ [====[Special-Missions/spm-timer.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Discover and hold the normal vr.c mission timer; no fixed stage/actor address.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if SPMTimer and SPMTimer.pid==getOpenedProcessID()then return SPMTimer end
if SPMTimer then SPMTimer.disable()end
local G=dofile(dir..'spm-inventory.lua')
local F={pid=G.pid,wanted=false,version=1,status='Mission timer freeze OFF',binds=0,writes=0}
local function u16(a)return assert(readSmallInteger(a),'Timer short unavailable')&amp;0xffff end
local function u32(a)return assert(readInteger(a),'Timer word unavailable')&amp;0xffffffff end
local function blob(a,n)
 local b=assert(readBytes(a,n,true),'Timer code unavailable');assert(#b==n,'Short timer read')
 local out={};for _,v in ipairs(b)do out[#out+1]=string.char(v)end;return table.concat(out)
end
local function hex(s)return(s:gsub('%x%x',function(v)return string.char(tonumber(v,16))end))end
local header=hex('d0ffbd272000b0af21808000c800042421288000213080002800bfaf82ef000c2400b1af1801028e0000000001004230e8004014')
local counter=hex('1801028e000000004210020001004230190040140e80113c0e80023ca04e438c010002241400621400000000340002963600038601004224340002a600140200031402000c00621421200000')
local draw=hex('eb51043c36000386340002861f858434232862001800a400c317050010c00000c3181800')
local die=hex('e8ffbd27211080001000bfaf4800448c00000000040080100000000034004584')
local function profile(r,act,death)
 assert(act&gt;=0x800c0000 and act+0x7a0&lt;0x80160000 and act%4==0 and death==act+0x780,'Unsupported timer actor callbacks')
 local o=act&amp;0x1fffff
 assert(blob(r+o,#header)==header and blob(r+o+0xe4,#draw)==draw and blob(r+(death&amp;0x1fffff),#die)==die,'Unsupported native timer layout')
 local b=blob(r+o+0x35c,#counter)
 for i=0,#counter//4-1 do
  local actual,expected=string.unpack('&lt;I4',b,i*4+1),string.unpack('&lt;I4',counter,i*4+1)
  local mask=(i==5 or i==6 or i==7)and 0xffff0000 or 0xffffffff
  assert(actual&amp;mask==expected&amp;mask,'Timer increment/expiry code differs')
 end
 local high=string.unpack('&lt;I4',b,6*4+1)&amp;0xffff
 local low=string.unpack('&lt;I4',b,7*4+1)&amp;0xffff;if low&gt;=32768 then low=low-65536 end
 local mode=(high&lt;&lt;16)+low
 assert(mode&gt;=0x800c0000 and mode+4&lt;0x80160000,'Timer play-mode binding invalid')
 return {mode=mode&amp;0x1fffff,act=act,die=death,proof=b}
end
function F.inspect()
 assert(getOpenedProcessID()==F.pid,'Attached process changed')
 local c=G.context(false);local r=c.ram
 assert(c.stage:match('^vr_[%w_]+$'),'Enter a VR mission')
 local start=0xadc90+5*0x44;local finish=start+0x20
 local previous=start;local p=u32(r+start+4);local seen={};local found
 for _=1,256 do
  assert(p&gt;=0x80010000 and p+0x120&lt;=0x80200000,'Timer actor pointer invalid')
  local o=p&amp;0x1fffff
  assert(u32(r+o)==0x80000000+previous,'Timer actor list changed')
  if o==finish then break end
  assert(not seen[o],'Timer actor list cycle');seen[o]=true
  local n=u32(r+o+20)
  if n&gt;=0x80010000 and n&lt;0x80200000 and readString(r+(n&amp;0x1fffff),48)=='vr.c' then
   assert(not found,'Multiple mission timer actors');found=o
  end
  previous=o;p=u32(r+o+4)
 end
 assert((p&amp;0x1fffff)==finish and found,'Normal mission timer actor unavailable')
 c.actor=found;c.profile=profile(r,u32(r+found+8),u32(r+found+12))
 c.elapsed=u16(r+found+0x34);c.limit=u16(r+found+0x36)
 c.timerFlags=u32(r+found+0x118);c.mode=u32(r+c.profile.mode)
 c.display=assert(readBytes(r+found+0x44,1))
 c.menu=u16(r+0xbe758+0x2a);c.remaining=c.limit-c.elapsed
 c.ready=c.ready and c.mode==1 and c.timerFlags&amp;2==0 and c.menu==0 and u32(r+0xac44c)&amp;0x10000000==0 and assert(readBytes(r+found+0x10b,1))==0
 c.supported=c.display==1 and c.limit&gt;0 and c.limit&lt;32768 and c.elapsed&lt;32768
 return c
end
function F.tick()
 if not F.wanted or F.busy then return end
 if getOpenedProcessID()~=F.pid then F.disable();F.status='Stopped: process changed';return end
 F.busy=true
 local ok,err=pcall(function()
  local c=F.inspect()
  assert(c.supported,'Mission does not use the supported visible timer')
  if not c.ready then F.binding=nil;F.status='Waiting for active mission play';return end
  local key=c.ram..':'..c.stage..':'..c.actor..':'..c.profile.act..':'..c.limit
  local b=F.binding
  if not b or b.key~=key or c.elapsed&lt;b.held then
   assert(c.remaining&gt;=15,'Restart mission: timer is expired or too close to expiry')
   b={key=key,held=c.elapsed,ram=c.ram,actor=c.actor,act=c.profile.act,die=c.profile.die,limit=c.limit,stage=c.stage}
   F.binding=b;F.binds=F.binds+1
  end
  -- Only the actor-owned elapsed counter is held. The global clock, limit,
  -- AI, animation, scores and native instructions are never written here.
  if c.elapsed~=b.held then
   assert(u32(c.ram+c.actor+8)==b.act and u32(c.ram+c.actor+12)==b.die and u16(c.ram+c.actor+0x36)==b.limit and u32(c.ram+c.profile.mode)==1,'Timer owner/state changed')
   assert(writeSmallInteger(c.ram+c.actor+0x34,b.held),'Could not hold mission timer');F.writes=F.writes+1
  end
  F.state=c;F.status=string.format('Timer freeze ON | %s | %d native timer ticks left | binds %d',c.stage,(c.limit-b.held),F.binds)
 end)
 if not ok then F.binding=nil;F.state=nil;F.status='Waiting: '..tostring(err)end
 F.busy=false
end
function F.enable()
 assert(F.pid==getOpenedProcessID(),'Attached process changed')
 F.wanted=true
 if not F.timer then F.timer=createTimer(nil,false);F.timer.Interval=10;F.timer.OnTimer=F.tick end
 F.timer.Enabled=true;F.tick();return true
end
function F.disable()
 F.wanted=false;if F.timer then F.timer.Enabled=false;F.timer.destroy();F.timer=nil end
 F.binding=nil;F.state=nil;F.status='Mission timer freeze OFF; normal ticking resumes'
 return true
end
SPMTimer=F;return F
]====]):sub(2),
 [ [====[Special-Missions/spm-toggles.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- Optional data-only cheats for the validated Special Missions EUR layout.
-- No game code patches, injected calls or debugger attachment.
if SPMToggles then
 assert(SPMToggles.pid==getOpenedProcessID(),'Stop the old controller before changing processes')
 return SPMToggles
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=SPMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'spm-reader.lua')end
local T={pid=R.pid,reader=R,version=2,health={enabled=false,requested=false,rebinds=0,status='OFF'},ammo={enabled=false,status='OFF'},stopped=false}
local INV=0x800000
local MASK=0x96
local function u16(address)return assert(readSmallInteger(address),'Cannot read 16-bit value')&amp;0xffff end
local function u32(address)return assert(readInteger(address),'Cannot read 32-bit value')&amp;0xffffffff end
local function put16(address,value,mask)
 assert(writeSmallInteger(address,value&amp;0xffff),'16-bit write failed')
 if mask~=false then
  mask=mask or 0xffff
  assert(u16(address)&amp;mask==(value&amp;mask),'16-bit verification failed')
 end
end
local function put32(address,value,mask)
 assert(writeInteger(address,value&amp;0xffffffff),'32-bit write failed')
 mask=mask or 0xffffffff
 assert(u32(address)&amp;mask==(value&amp;mask),'32-bit verification failed')
end
local function put8(address,value)
 assert(writeBytes(address,value&amp;255),'Byte write failed')
 assert(readBytes(address,1)==value,'Byte verification failed')
end
local function fingerprint(address,expected)
 local actual=readBytes(address,#expected,true)
 assert(actual and #actual==#expected,'Protection code unavailable')
 for i,v in ipairs(expected)do assert(actual[i]==v,'Unsupported protection code fingerprint')end
end
local function psx(pointer,size)
 assert(pointer and pointer&gt;=0x80000000 and pointer&lt;0x80200000,'Invalid PlayStation pointer')
 local offset=pointer&amp;0x1fffff
 assert(offset+(size or 1)&lt;=0x200000,'PlayStation object exceeds RAM')
 return offset
end
function T.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xac450)==0 and u32(ram+0xacab0)~=0,'Area loading')
 local control=u32(ram+0xaca6c)
 local work=psx(control,0x100)-0x20
 assert(work&gt;=0 and work+0xa24&lt;0x200000,'Invalid Snake actor bounds')
 assert(u32(ram+work+8)==0x8005d6e4 and u32(ram+work+0xc)==0x8005dd38,'Snake actor is not live')
 assert(u32(ram+0xaca98)==0x80000000+work+0x9c,'Snake body owner mismatch')
 local target=psx(u32(ram+work+0x898),0x48)
 assert(u16(ram+target+2)==1,'Collision target is not on the player side')
 return {h=h,ram=ram,work=work,target=target,status=ram+0xacac8}
end
local function sameOwner(c,s)
 return c.ram==s.ram and c.work==s.work and c.target==s.target
end
local function checkCode(ram)
 R.checkFeature('health');R.checkFeature('ammo')
end
local function applyHealth(c,s)
 assert(sameOwner(c,s),'Snake actor/RAM changed; stop and re-enable protection in gameplay')
 -- Match the game's invulnerability state. Zero frames means no expiration.
 local status=u32(c.status)
 if status&amp;INV==0 then put32(c.status,status|INV,INV)end
 if readBytes(c.ram+c.work+0xa20,1)~=0 then put8(c.ram+c.work+0xa20,0)end
 local class=u16(c.ram+c.target)
 if class&amp;MASK~=0 then put16(c.ram+c.target,class&amp;(~MASK&amp;0xffff),MASK)end
end
local function restoreHealth(s)
 if not s.owner then return true end
 assert(getOpenedProcessID()==T.pid,'Cannot restore while attached to another process')
 local c=T.context()
 if not sameOwner(c,s.owner)then
  -- The original actor has been replaced. Its old fields are no longer ours
  -- to write; the new actor was not patched by this ownership record.
  s.owner=nil;return true
 end
 -- Restore only our collision-mask bits, preserving unrelated current flags.
 put16(c.ram+c.target,(u16(c.ram+c.target)&amp;(~MASK&amp;0xffff))|s.originalMask,MASK)
 put8(c.ram+c.work+0xa20,0)
 put32(c.status,u32(c.status)&amp;(~INV&amp;0xffffffff),INV)
 s.owner=nil
 return true
end
local function applyAmmo(c)
 local h=c.h
 for i=1,10 do
  local current,capacity=h.ammo[i],h.ammoMax[i]
  -- Leave unowned weapons and undefined capacities alone.
  if current&gt;=0 and capacity&gt;0 and capacity&lt;=32767 and current&lt;capacity then
   put16(c.ram+0xb5e32+(i-1)*2,capacity,false)
  end
 end
 -- These three firearms use the shared magazine fields. Never change capacity.
 if h.weapon==0 or h.weapon==1 or h.weapon==9 then
  local capacity=h.magazineMax
  if capacity&gt;0 and capacity&lt;=500 and h.magazine&gt;=0 and h.magazine&lt;capacity then
   local total=h.ammoMax[h.weapon+1]
   if total&gt;0 then put16(c.ram+0xaca64,math.min(capacity,total),false)end
  end
 end
end
function T.disable(kind)
 local s=assert(T[kind],'Unknown option')
 s.enabled=false
 if kind=='health'then s.requested=false end
 if kind=='health'and s.owner then
  local ok,err=pcall(restoreHealth,s)
  if not ok then s.status='RESTORE PENDING: '..tostring(err);return false,s.status end
 end
 s.status='OFF'
 return true
end
function T.enable(kind)
 assert(not T.stopped,'Reload the stopped controller')
 local s=assert(T[kind],'Unknown option')
 if s.enabled then return true end
 assert(not s.owner,'Finish pending health restoration before re-enabling')
 local c=T.context();checkCode(c.ram)
 assert(c.h.health&gt;0 and u32(c.ram+0xac454)==0,'Enter normal living gameplay before enabling')
 if kind=='health'then
  local existing=u32(c.status)&amp;INV~=0
  local frames=assert(readBytes(c.ram+c.work+0xa20,1),'Cannot read invulnerability frames')
  assert(not existing or (frames&gt;0 and frames&lt;128)or s.resumeOwned,'An existing permanent invulnerability state is active; leave it unchanged')
  -- A normal hit's temporary immunity can be extended. OFF then performs its
  -- normal expiration mask, rather than preserving that temporary no-hit mask.
  s.originalMask=existing and MASK or (u16(c.ram+c.target)&amp;MASK)
  s.owner={ram=c.ram,work=c.work,target=c.target}
  local ok,err=pcall(function()
   applyHealth(c,s.owner)
   -- Synchronize the three health values once; no health-value freeze loop.
   put16(c.ram+c.target+0x26,c.h.maximum)
   put16(c.ram+c.work+0xa1e,c.h.maximum)
   put16(c.ram+0xb5e26,c.h.maximum)
  end)
  if not ok then
   local restored,restoreError=pcall(restoreHealth,s)
   s.status=restored and ('OFF: '..tostring(err))or ('RESTORE PENDING: '..tostring(restoreError))
   error(s.status)
  end
  s.status='ON - native invulnerability + initial heal'
  s.requested=true;s.resumeOwned=nil
 elseif kind=='ammo'then
  applyAmmo(c);s.ram=c.ram;s.work=c.work
  s.status='ON - owned ammo/magazines replenish'
 else error('Unknown option')end
 s.enabled=true
 return true
end
function T.tick()
 if T.stopped then return end
 if not T.health.requested and not T.ammo.enabled and not T.health.owner then return end
 -- Retry our own pending restoration when gameplay becomes readable again.
 if not T.health.requested and T.health.owner then T.disable('health')end
 if not T.health.requested and not T.ammo.enabled then return end
 local ok,c=pcall(T.context)
 if not ok then
  local ammoWasEnabled=T.ammo.enabled
  T.health.enabled=false;T.ammo.enabled=false
  if ammoWasEnabled then T.ammo.status='OFF: '..tostring(c)end
  if T.health.requested then T.health.status='WAITING FOR AREA: '..tostring(c)
  elseif T.health.owner then T.health.status='RESTORE PENDING: '..tostring(c)end
  return
 end
 if T.health.requested then
  local rebound=T.health.owner and not sameOwner(c,T.health.owner)
  if rebound then
   T.health.resumeOwned=T.health.owner.ram==c.ram
   T.health.owner=nil;T.health.enabled=false
  end
  local applied,err=pcall(function()
   if not T.health.owner then T.health.enabled=false;T.enable('health')
   else applyHealth(c,T.health.owner)end
  end)
  if not applied then
   T.health.enabled=false;T.health.status='WAITING FOR AREA: '..tostring(err)
  else
   if rebound then T.health.rebinds=T.health.rebinds+1 end
   T.health.enabled=true;T.health.status='ON - native invulnerability | area rebinds '..T.health.rebinds
  end
 end
 if T.ammo.enabled then
  if c.ram~=T.ammo.ram or c.work~=T.ammo.work then
   T.ammo.enabled=false;T.ammo.status='OFF: actor/RAM changed; re-enable in gameplay'
  else
   local applied,err=pcall(applyAmmo,c)
   if not applied then T.ammo.enabled=false;T.ammo.status='OFF: '..tostring(err)end
  end
 end
end
function T.stopAll()
 local restored=T.disable('health');T.disable('ammo')
 if not restored then return false,T.health.status end
 T.stopped=true;T.timer.Enabled=false;T.timer.destroy();T.timer=nil
 if SPMToggles==T then SPMToggles=nil end
 return true
end
T.timer=createTimer(nil,false);T.timer.Interval=50;T.timer.OnTimer=T.tick;T.timer.Enabled=true
SPMToggles=T
return T
]====]):sub(2),
 [ [====[Special-Missions/spm-unlocks.lua]====] ]=([====[!-- Generated by analysis/build-special-missions.py.
-- European Special Missions menu access only. No completion flags, times or saves edited.
if SPMUnlocks then
 assert(SPMUnlocks.pid==getOpenedProcessID(),'Stop the previous unlock controller before changing processes')
 return SPMUnlocks
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=SPMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'spm-reader.lua')end
local U={pid=R.pid,enabled=false,wanted=false,status='OFF',reader=R,version=1}
local MASK=0x40000000
local GROUPS=0xd1070
local function u32(a)return assert(readInteger(a),'Menu word unavailable')&amp;0xffffffff end
local function u16(a)return assert(readSmallInteger(a),'Menu short unavailable')&amp;0xffff end
local function psx(p,n)
 assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'Menu pointer outside RAM')
 return p&amp;0x1fffff
end
local function fp(r,o,hex)
 local expected=hex:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)
 local b=assert(readBytes(r+o,#expected,true),'Menu code unavailable')
 assert(#b==#expected and string.char(table.unpack(b))==expected,'Unsupported VR menu code at '..string.format('%X',o))
end
function U.context()
 assert(getOpenedProcessID()==U.pid and process=='METAL GEAR SOLID.exe','Attached process changed')
 assert(getModuleSize(process)==30007296 and readQword(R.owner)==R.vtable,'Emulator owner differs')
 local r=readQword(R.owner+0x28)
 assert(r and readString(r+0x10000,11)=='SLES_021.36','European Special Missions guest required')
 local stage=readString(r+0xb5e00,16)
 if stage~='selectvr'then return nil,'Outside mission-select menu'end
 assert(u32(r+0xac450)==0,'Mission-select menu is loading')
 -- Confirm handler tests availability; renderer tests the same bit.
 fp(r,0xe1294,'0000638C0040023C24106200070040140020023C')
 fp(r,0xde2c0,'0000E28C0040033C24104300100040105800A524')
 -- Normal progression unlocks Special by ORing availability into root+0xb4.
 fp(r,0xdfab4,'701063240800648C00000000B400828C0040053C25104500B40082AC')
 -- Native header lookup uses 28-byte groups and group+8 child pointers.
 fp(r,0xda3e8,'0D80023C70104224C01804002318640080180300211862000400628C0800648C')
 local root=0xadc90
 for level=0,8 do
  local head=root+level*0x44;local tail=head+0x20
  assert(u32(r+head)==0 and u32(r+head+8)==0 and u32(r+head+12)==0 and u32(r+tail+4)==0 and u32(r+tail+8)==0 and u32(r+tail+12)==0,'Resident actor sentinels differ')
 end
 local head=root+7*0x44;local previous=head;local pointer=u32(r+head+4)
 local seen,managers={},{}
 for n=1,128 do
  local w=psx(pointer,0x374)
  if w==head+0x20 then assert(u32(r+w)==0x80000000+previous,'Menu actor tail changed');break end
  assert(not seen[w]and u32(r+w)==0x80000000+previous,'Menu actor list changed');seen[w]=true
  local np=u32(r+w+20)
  if np&gt;=0x80000000 and np&lt;0x80200000 and readString(r+psx(np),32)=='winmngr.c'then
   assert(u32(r+w+8)==0x800e1bb0 and u32(r+w+12)==0x800e273c,'Menu actor callbacks differ')
   managers[#managers+1]={work=w,namePointer=np}
  end
  previous=w;pointer=u32(r+w+4);assert(n&lt;128,'Menu actor count exceeds limit')
 end
 assert(#managers==1,'Expected one live mission-select manager')
 local manager=managers[1]
 local group=u16(r+manager.work+0x2ce)
 assert(group&lt;=70,'Menu navigation group differs')
 local c={ram=r,stage=stage,manager=manager,group=group,fields={},groups={}}
 local targets={}
 local function add(o,g,index)
  assert(not targets[o],'Overlapping menu options');targets[o]=true
  local flags=u32(r+o)
  assert(flags&amp;0x80000000~=0,'Menu option header differs')
  local art=u32(r+o+4);psx(art,4)
  c.fields[#c.fields+1]={offset=o,flags=flags,art=art,group=g,index=index}
 end
 assert(u32(r+GROUPS+4)==6 and u32(r+GROUPS+8)==0x800c56a0,'Main category table differs')
 local entries=psx(u32(r+GROUPS+8),6*0x3c)
 for _,target in ipairs({{index=2,name='advanced_mode',destination=3},{index=3,name='special_mode',destination=4}})do
  local o=entries+target.index*0x3c
  local art=u32(r+o+4);local name=u32(r+psx(art,4))
  assert(readString(r+psx(name,1),32)==target.name,'Category name differs')
  assert(u16(r+o+0x22)==target.destination,'Category destination differs')
  add(o,0,target.index)
 end
 for g=0,70 do
  local o=GROUPS+g*0x1c
  local count,pointer,meta=u32(r+o+4),u32(r+o+8),u32(r+o+12)
  assert(count&gt;=1 and count&lt;=15,'Unexpected menu group size')
  local first=psx(pointer,count*0x3c)
  assert(first&gt;=0xc0000 and first+count*0x3c&lt;=0xd1070,'Menu option array differs')
  local parent=meta&amp;0xffff
  if g==3 or g==4 or parent==3 or parent==4 then
   c.groups[#c.groups+1]={index=g,offset=o,count=count,pointer=pointer,meta=meta}
   for i=0,count-1 do add(first+i*0x3c,g,i)end
  end
 end
 assert(#c.groups==37 and #c.fields==198,'Unexpected Advanced/Special menu structure')
 c.epoch=tostring(r)..':'..manager.work..':'..manager.namePointer
 return c
end
local function put(r,o,v)
 assert(writeInteger(r+o,v&amp;0xffffffff),'Menu access write failed')
 assert(u32(r+o)&amp;MASK==v&amp;MASK,'Menu access verification failed')
end
function U.apply()
 local c,why=U.context()
 if not c then U.snapshot=nil;U.enabled=false;U.status='WAITING: '..why;return false end
 local fresh=U.context()
 assert(fresh and fresh.epoch==c.epoch,'Menu changed during access preflight')
 local s=U.snapshot
 if not s or s.epoch~=c.epoch then s={epoch=c.epoch,ram=c.ram,original={},identity={}};U.snapshot=s end
 -- Validate the complete plan before the first write.
 for _,v in ipairs(c.fields)do
  assert(u32(c.ram+v.offset+4)==v.art and u32(c.ram+v.offset)==v.flags,'Menu options changed')
  if s.identity[v.offset]then assert(s.identity[v.offset]==v.art,'Menu option identity changed')
  else s.identity[v.offset]=v.art;s.original[v.offset]=v.flags&amp;MASK end
 end
 local changed=0
 for _,v in ipairs(c.fields)do
  if v.flags&amp;MASK==0 then put(c.ram,v.offset,u32(c.ram+v.offset)|MASK);changed=changed+1 end
 end
 U.enabled=true;U.count=#c.fields;U.changed=changed;U.stage=c.stage
 U.status='ON - Advanced + Special access | '..#c.fields..' menu options | records unchanged'
 return true
end
function U.enable()
 assert(not U.stopped,'Reload the stopped unlock controller')
 if U.wanted then return true end
 local c,why=U.context();assert(c,why)
 U.wanted=true
 local ok,err=pcall(U.apply)
 if not ok then
  U.wanted=false;U.enabled=false
  local restored,cleanup=pcall(U.disable)
  U.status=(restored and cleanup)and ('ERROR: '..tostring(err))or ('CLEANUP WAITING: '..tostring(err))
  error(U.status)
 end
 if not U.timer then U.timer=createTimer(nil,false);U.timer.Interval=1000;U.timer.OnTimer=U.tick end
 U.timer.Enabled=true
 return true
end
function U.disable()
 U.wanted=false;U.enabled=false
 if U.timer then U.timer.Enabled=false end
 if U.snapshot then
  local ok,c=pcall(U.context)
  if not ok then U.status='CLEANUP WAITING: '..tostring(c);return false,U.status end
  if c and c.epoch==U.snapshot.epoch then
   for _,v in ipairs(c.fields)do
    local original=U.snapshot.original[v.offset]
    assert(original~=nil and U.snapshot.identity[v.offset]==v.art,'Menu restoration identity differs')
    put(c.ram,v.offset,(u32(c.ram+v.offset)&amp;(~MASK&amp;0xffffffff))|original)
   end
  end
 end
 U.snapshot=nil;U.status='OFF';return true
end
function U.tick()
 if not U.wanted then return end
 if getOpenedProcessID()~=U.pid then
  U.wanted=false;U.enabled=false;U.snapshot=nil
  U.timer.Enabled=false;U.status='Stopped: attached process changed';return
 end
 local ok,err=pcall(U.apply)
 if not ok then U.enabled=false;U.status='WAITING: '..tostring(err)end
end
function U.stop()
 local ok,err=U.disable();if not ok then return false,err end
 if U.timer then U.timer.destroy();U.timer=nil end
 U.stopped=true;if SPMUnlocks==U then SPMUnlocks=nil end;return true
end
SPMUnlocks=U
return U
]====]):sub(2),
 [ [====[statistics-panel.lua]====] ]=([====[!-- Table-style statistics editor. Its refresh timer performs target reads only.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if MGSStatisticsPanel and MGSStatisticsPanel.pid==getOpenedProcessID()then MGSStatisticsPanel.show();return MGSStatisticsPanel end
if MGSStatisticsPanel then MGSStatisticsPanel.stop()end
local S=dofile(dir..'mgs-stats.lua')
local P={pid=S.pid,stopped=false,rows={}}
local form=createForm(false);P.form=form;form.Caption='Metal Gear Solid - Game Statistics'
form.Width=775;form.Height=655;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local function label(x,y,text,width)
 local l=createLabel(form);l.Left=x;l.Top=y;l.Caption=text
 if width then l.AutoSize=false;l.Width=width;l.Height=36;l.WordWrap=true end
 return l
end
local function edit(x,y,width)
 local e=createEdit(form);e.Left=x;e.Top=y;e.Width=width;return e
end
local function button(x,y,width,text,fn)
 local b=createButton(form);b.Left=x;b.Top=y;b.Width=width;b.Height=28;b.Caption=text;b.OnClick=fn;return b
end
local function action(fn)
 local ok,err=pcall(fn);P.error=not ok and tostring(err)or nil;P.tick()
end
label(16,10,'Ranking statistics - changes apply only when you click Apply.')
P.info=label(16,36,'',735)
label(16,79,'Statistic');label(282,79,'Current');label(400,79,'New value')
for i,e in ipairs(S.fields)do
 local y=105+(i-1)*34;local row={field=e};P.rows[i]=row
 label(16,y+4,e.name);row.current=label(282,y+4,'--')
 row.input=edit(400,y,115)
 row.apply=button(540,y,100,'Apply',function()action(function()S.setCounter(e.key,row.input.Text)end)end)
end
label(16,390,'Play time (HH : MM : SS)');P.timeCurrent=label(282,390,'--')
P.hours=edit(400,385,57);P.minutes=edit(464,385,48);P.seconds=edit(519,385,48)
P.applyTime=button(590,385,150,'Apply play time',function()action(function()S.setTime(P.hours.Text,P.minutes.Text,P.seconds.Text)end)end)
P.copy=button(400,423,205,'Copy current to inputs',function()
 action(function()
  local c=S.inspect()
  for _,row in ipairs(P.rows)do row.input.Text=tostring(c.values[row.field.key])end
  P.hours.Text=tostring(c.hours);P.minutes.Text=tostring(math.floor(c.seconds/60));P.seconds.Text=tostring(c.seconds%60)
 end)
end)
P.extra=label(16,463,'',730)
label(16,504,'Edits stay in this run and may be stored by a normal save. No counters are frozen.',730)
label(16,541,'Difficulty and special-item use can also affect rank. This editor does not predict a final grade.',730)
P.status=label(16,582,'',735);P.status.Height=54
function P.tick()
 if P.stopped then return end
 if not MGSDashboard or MGSDashboard.stopped then P.stop();return end
 local ok,c=pcall(S.inspect);P.state=ok and c or nil
 local ready=ok and c.ready
 for _,row in ipairs(P.rows)do row.current.Caption=ok and tostring(c.values[row.field.key])or '--';row.apply.Enabled=not not ready end
 P.applyTime.Enabled=not not ready;P.copy.Enabled=not not ready
 P.timeCurrent.Caption=ok and c.playTime or '--'
 P.info.Caption=ok and ('Area: '..c.stage..' | Difficulty: '..c.difficulty..' (read-only)')or 'Waiting for normal gameplay.'
 P.extra.Caption=ok and ('Stage time: '..c.stageTime..' | Last-save time: '..c.lastSaveTime..' (read-only)')or ''
 P.status.Caption=P.error or (not ok and tostring(c))or S.status
 if S.logError then P.status.Caption=P.status.Caption..' Log: '..S.logError end
 -- Initialize once; refresh never overwrites text the user is editing.
 if ok and not P.initialized then
  for _,row in ipairs(P.rows)do row.input.Text=tostring(c.values[row.field.key])end
  P.hours.Text=tostring(c.hours);P.minutes.Text=tostring(math.floor(c.seconds/60));P.seconds.Text=tostring(c.seconds%60);P.initialized=true
 end
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if MGSStatisticsPanel==P then MGSStatisticsPanel=nil end
 local r=getAddressList().getMemoryRecordByID(6)
 if r and r.Description:match('^Game statistics editor')and r.Active then r.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=500;timer.OnTimer=P.tick
MGSStatisticsPanel=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[VR-Missions/dashboard.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- CE-side window and change log. All game access is through read-only reads.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if VRMDashboard then
 VRMDashboard.stop()
 assert(not VRMDashboard,'Close the previous dashboard before reloading')
end
local R=dofile(dir..'vrm-reader.lua')
local D={reader=R,pid=R.pid,samples=0,changes=0,errors=0,label='baseline',stopped=false}
local logPath=dir..'../../logs/vrm-state-'..R.pid..'-'..os.date('!%Y%m%dT%H%M%SZ')..'.csv'
local csv=assert(io.open(logPath,'w'));D.logPath=logPath
local columns={'utc','label','health','max_health','weapon_id','item_id','total_ammo','ammo_capacity','magazine','mag_capacity','alert_mode','alert_level','ration','ration_capacity'}
for i=1,10 do columns[#columns+1]='ammo_'..(i-1)end
csv:write(table.concat(columns,',')..'\n');csv:flush()
local form=createForm(false);D.form=form;form.Caption='VR Missions - Monitor';form.Width=660;form.Height=700
form.Position='poScreenCenter'
local memo=createMemo(form);D.memo=memo;memo.Align='alClient';memo.ReadOnly=true;memo.ScrollBars='ssVertical';memo.WordWrap=false
memo.Font.Name='Consolas';memo.Font.Size=11
local function value(v)return v==nil and '--'or tostring(v)end
local function csvValue(v)return '"'..tostring(v or ''):gsub('"','""')..'"'end
function D.mark(label)
 assert(type(label)=='string'and #label&lt;=80,'Short test label required')
 D.label=label;D.last=nil
end
local function display(h)
 local rows={'READ-ONLY MONITOR | Steam build 20872173 | US VR Missions',
  'VR port: readings checked; gameplay effects need VR-specific validation','',
  string.format('Health       %d / %d (%.1f%%)',h.health,h.maximum,100*h.health/h.maximum),
  'Weapon       '..h.weaponName,
  'Total ammo   '..value(h.ammoSelected)..' / '..value(h.ammoSelectedMax),
  'Magazine     '..((h.weapon==0 or h.weapon==1)and (h.magazine..' / '..h.magazineMax)or 'N/A')}
 -- The inventory count includes rounds in the magazine; it is not spare ammo.
 rows[#rows+1]='Rations      '..h.ration..' / '..h.rationMax
 rows[#rows+1]='';rows[#rows+1]='Alert mode   '..h.alertName..' ('..h.alertMode..')'
 rows[#rows+1]='Alert level  '..h.alertLevel..' (raw; not assumed seconds/percent)'
 rows[#rows+1]='';rows[#rows+1]='Inventory ammo (total / capacity)'
 for i,name in ipairs(R.weapons)do
  rows[#rows+1]=string.format('  %-15s %s',name,h.ammo[i]&lt;0 and 'Not owned'or (h.ammo[i]..' / '..h.ammoMax[i]))
 end
 rows[#rows+1]='';rows[#rows+1]='Sample every 100 ms | F7 hide/show | Close to stop'
 rows[#rows+1]='Monitor reads only. Optional cheats are separate CT entries.'
 if VRMToggles then
  rows[#rows+1]='Health protection: '..VRMToggles.health.status
  rows[#rows+1]='Unlimited ammo: '..VRMToggles.ammo.status
 end
 if VRMNoAlert then rows[#rows+1]='No alert: '..VRMNoAlert.status end
 rows[#rows+1]='Test: '..D.label..' | samples '..D.samples..' | changes '..D.changes
 if D.logError then rows[#rows+1]='Logging stopped: '..D.logError end
 memo.Lines.Text=table.concat(rows,'\r\n')
end
function D.tick()
 if D.stopped then return end
 local ok,h=pcall(R.read)
 if not ok then
  D.state=nil;D.errors=D.errors+1;D.error=tostring(h)
  memo.Lines.Text='READ ONLY | Waiting for valid gameplay\r\n'..D.error..'\r\nPrevious values cleared.'
  return
 end
 D.state=h;D.error=nil;D.samples=D.samples+1
 local fields={D.label,h.health,h.maximum,h.weapon,h.item,value(h.ammoSelected),value(h.ammoSelectedMax),h.magazine,h.magazineMax,h.alertMode,h.alertLevel,h.ration,h.rationMax}
 for i=1,10 do fields[#fields+1]=h.ammo[i]end
 local row={};for _,v in ipairs(fields)do row[#row+1]=csvValue(v)end;row=table.concat(row,',')
 if row~=D.last then
  D.changes=D.changes+1;D.last=row
  if csv then
   local logged,err=pcall(function()
    assert(csv:write(os.date('!%Y-%m-%dT%H:%M:%SZ')..','..row..'\n'));assert(csv:flush())
    if csv:seek()&gt;10*1024*1024 then csv:close();csv=nil;D.logError='10 MiB log limit reached'end
   end)
   if not logged then D.logError=tostring(err);pcall(function()csv:close()end);csv=nil end
  end
 end
 display(h)
end
function D.stop(closing)
 if D.stopped then return true end
 D.stopped=true
 if D.timer then D.timer.Enabled=false;D.timer.destroy();D.timer=nil end
 if D.hotkey then D.hotkey.destroy();D.hotkey=nil end
 if csv then csv:close();csv=nil end
 if not closing then form.OnClose=nil;form.destroy()end
 if VRMDashboard==D then VRMDashboard=nil end
 -- Closing the diagnostic window affects only its own CT entry.
 local r=getAddressList().getMemoryRecordByID(301)
 if r and r.Description:match('^Dashboard')and r.Active then r.Active=false end
 return true
end
form.OnClose=function()local ok=D.stop(true);return ok and caFree or caNone end
D.hotkey=createHotkey(function()form.Visible=not form.Visible end,0x76)
local timer=createTimer(form,false);D.timer=timer;timer.Interval=100;timer.OnTimer=D.tick
VRMDashboard=D;D.tick();timer.Enabled=true;form.show()
return D
]====]):sub(2),
 [ [====[VR-Missions/guard-state-panel.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if VRMGuardStatePanel and VRMGuardStatePanel.pid==getOpenedProcessID()then VRMGuardStatePanel.show();return VRMGuardStatePanel end
if VRMGuardStatePanel then VRMGuardStatePanel.stop()end
local A=dofile(dir..'vrm-guard-state.lua')
local C=dofile(dir..'vrm-guard-proximity.lua')
local P={pid=A.pid,actions=A,stopped=false}
local f=createForm(false);P.form=f;f.Caption='VR Missions - Guard state'
f.Width=760;f.Height=655;f.Position='poScreenCenter';f.Font.Name='Segoe UI';f.Font.Size=10
local function label(y,s)
 local v=createLabel(f);v.Left=16;v.Top=y;v.AutoSize=false;v.Width=720;v.Height=40;v.WordWrap=true;v.Caption=s;return v
end
label(12,'One-shot actions for standard guards loaded in the current area.')
label(48,'Knockout preserves health. Extended knockout delays recovery. Kill follows normal death logic and can increase the kill count.')
label(94,'Busy, already down, and unsupported guards are skipped. Cameras, bosses, civilians and Snake are excluded.')
local info=label(138,'');info.Height=48
local memo=createMemo(f);memo.Left=16;memo.Top=266;memo.Width=720;memo.Height=160;memo.ReadOnly=true;memo.ScrollBars='ssVertical'
local status=label(435,'');status.Height=60
local extended=createCheckBox(f);extended.Left=16;extended.Top=190;extended.Caption='Extended knockout (~60 seconds)';extended.Checked=true
local dl=createLabel(f);dl.Left=332;dl.Top=194;dl.Caption='Delay (seconds):'
local delay=createEdit(f);delay.Left=459;delay.Top=189;delay.Width=46;delay.Text='5'
local cancel=createButton(f);cancel.Left=535;cancel.Top=186;cancel.Width=201;cancel.Height=28;cancel.Caption='Cancel scheduled action';cancel.Enabled=false
local buttons={}
local function button(x,width,text,fn)
 local b=createButton(f);b.Left=x;b.Top=225;b.Width=width;b.Height=30;b.Caption=text;b.OnClick=fn;return b
end
function P.refresh()
 if P.stopped then return end
 local ok,c=pcall(A.inspect);P.state=ok and c or nil
 buttons[1].Enabled=ok and c.eligible&gt;0 and not P.pending or false;buttons[2].Enabled=buttons[1].Enabled
 local lines={}
 if ok then
  info.Caption=string.format('Area: %s | Loaded: %d | Ready: %d | Knocked out: %d | Dead: %d | Busy: %d',c.stage,c.total,c.eligible,c.knockedOut,c.dead,c.skipped)
  for _,g in ipairs(c.guards)do lines[#lines+1]=string.format('Guard %d | HP %d | stun %d | %s',g.actor.slot,g.hp,g.faint,g.eligible and 'Ready'or g.reason)end
  if c.reason then lines[#lines+1]=c.reason end
 else info.Caption='Waiting for supported gameplay.';lines[1]=tostring(c)end
 memo.Lines.Text=table.concat(lines,'\r\n');status.Caption=P.error or A.status
 if A.logError then status.Caption=status.Caption..' Log: '..A.logError end
end
local function cancelPending()
 if P.pending then P.pending.Enabled=false;P.pending.destroy();P.pending=nil end;cancel.Enabled=false
end
cancel.OnClick=function()cancelPending();P.error=nil;A.status='Scheduled action cancelled.';P.refresh()end
local function action(mode)
 P.error=nil
 local ok,err=pcall(function()
  local seconds=tonumber(delay.Text)
  assert(seconds and seconds==math.floor(seconds)and seconds&gt;=0 and seconds&lt;=15,'Delay must be 0..15 seconds.')
  local armed=A.inspect();local long=extended.Checked
  local function execute()
   cancelPending()
   local success,result=pcall(function()
    local c=A.inspect();assert(c.ram==armed.ram and c.stage==armed.stage,'Area changed; scheduled action cancelled.')
    local outcome=A.apply(mode)
    if mode=='knockout'and long then A.extendKnockout(outcome,1800)end
    return outcome
   end)
   P.error=not success and tostring(result)or nil;P.refresh()
  end
  cancelPending()
  if seconds==0 then execute();return end
  local timer=createTimer(nil,false);P.pending=timer;timer.Interval=1000;cancel.Enabled=true
  A.status=mode..' in '..seconds..' seconds. Switch back to the game.'
  timer.OnTimer=function()
   seconds=seconds-1
   if seconds&lt;=0 then execute()else status.Caption=mode..' in '..seconds..' seconds. Switch back to the game.'end
  end
  timer.Enabled=true
 end)
 P.error=not ok and tostring(err)or P.error;P.refresh()
end
buttons[1]=button(16,245,'Knock out loaded guards',function()action('knockout')end)
buttons[2]=button(275,245,'Kill loaded guards',function()action('kill')end)
button(535,201,'Refresh (read-only)',function()P.error=nil;P.refresh()end)
label(502,'Proximity: enable the VR knockout or kill checkbox. Only one mode runs at a time.')
local rl=createLabel(f);rl.Left=16;rl.Top=550;rl.Caption='Radius (game units):'
local radius=createEdit(f);radius.Left=178;radius.Top=545;radius.Width=80;radius.Text=tostring(C.radius)
local applyRadius=createButton(f);applyRadius.Left=275;applyRadius.Top=543;applyRadius.Width=150;applyRadius.Height=28;applyRadius.Caption='Apply radius'
local stopAuto=createButton(f);stopAuto.Left=445;stopAuto.Top=543;stopAuto.Width=165;stopAuto.Height=28;stopAuto.Caption='Stop proximity'
local autoStatus=label(583,'');autoStatus.Height=54
applyRadius.OnClick=function()
 local ok,err=pcall(C.setRadius,radius.Text);P.error=not ok and tostring(err)or nil;P.refresh()
end
stopAuto.OnClick=function()C.disable();P.error=nil;P.refresh()end
local statusTimer=createTimer(f,false);P.statusTimer=statusTimer;statusTimer.Interval=500
statusTimer.OnTimer=function()autoStatus.Caption=C.status end;statusTimer.Enabled=true;autoStatus.Caption=C.status
function P.show()f.show()end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 cancelPending();if A.extension then A.extension.stop()end
 if P.statusTimer then P.statusTimer.Enabled=false;P.statusTimer.destroy();P.statusTimer=nil end
 if not closing then f.OnClose=nil;f.destroy()end
 if VRMGuardStatePanel==P then VRMGuardStatePanel=nil end
 local row=getAddressList().getMemoryRecordByID(309)
 if row and row.Description:match('^Guard state')and row.Active then row.Active=false end
 return true
end
f.OnClose=function()P.stop(true);return caFree end
VRMGuardStatePanel=P;P.refresh();P.show();return P
]====]):sub(2),
 [ [====[VR-Missions/inventory-panel.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Inventory picker. Opening/refreshing this window only reads game state.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if VRMInventoryPanel and VRMInventoryPanel.pid==getOpenedProcessID()then
 VRMInventoryPanel.show();return VRMInventoryPanel
end
if VRMInventoryPanel then VRMInventoryPanel.stop()end
local G=dofile(dir..'vrm-inventory.lua')
local P={pid=G.pid,inventory=G,stopped=false}
local form=createForm(false);P.form=form;form.Caption='VR Missions - Weapon &amp; Gadget Selector'
form.Width=750;form.Height=675;form.Position='poScreenCenter';form.Font.Name='Segoe UI';form.Font.Size=10
local title=createLabel(form);title.Left=16;title.Top=10
title.Caption='Experimental VR equipment grants. Mission resources may limit usable equipment.'
local function label(parent,x,y,text)
 local l=createLabel(parent);l.Left=x;l.Top=y;l.Caption=text;return l
end
local function button(parent,x,y,text,action)
 local b=createButton(parent);b.Left=x;b.Top=y;b.Width=178;b.Height=30;b.Caption=text;b.OnClick=action;return b
end
local function displayName(kind,id)
 if id&lt;0 then return 'None'end
 local list=kind=='weapon'and G.weapons or G.gadgets
 return list[id+1]and list[id+1].name or '?'
end
local function errorText(err)return tostring(err):match(': ([^\r\n]+)$')or tostring(err)end
local rows={}
local function selected(row)return row.list[row.combo.ItemIndex+1]end
local function act(row,equipping)
 local e=assert(selected(row),'Select equipment')
 local ok,err=pcall(G.grant,row.kind,e.id,row.amount.Text,equipping)
 P.error=not ok and errorText(err)or nil
 if ok then G.status=e.name..(equipping and ' added; equipment switch requested.'or ' added to inventory.')end
 P.tick()
end
local function group(kind,y,caption,list)
 local box=createGroupBox(form);box.Left=12;box.Top=y;box.Width=710;box.Height=170;box.Caption=caption
 local row={kind=kind,list=list,group=box};rows[#rows+1]=row
 local combo=createComboBox(box);row.combo=combo;combo.Left=12;combo.Top=24;combo.Width=325;combo.Style='csDropDownList'
 for _,e in ipairs(list)do combo.Items.add(e.name)end
 row.amountLabel=label(box,355,27,kind=='weapon'and 'Ammo stock' or 'Stock')
 local amount=createEdit(box);row.amount=amount;amount.Left=475;amount.Top=22;amount.Width=95
 row.add=button(box,12,64,'Add to inventory',function()act(row,false)end)
 row.equip=button(box,200,64,'Add + equip',function()act(row,true)end)
 row.unequip=button(box,388,64,'Unequip',function()
  local ok,err=pcall(G.equip,kind,-1);P.error=not ok and errorText(err)or nil;P.tick()
 end)
 local info=label(box,12,105,'');row.info=info;info.AutoSize=false;info.WordWrap=true;info.Width=678;info.Height=53
 combo.OnChange=function()
  local e=selected(row);if e then amount.Text=tostring(e.stock or 1)end
  P.error=nil;if P.tick then P.tick()end
 end
 combo.ItemIndex=0;amount.Text=tostring(list[1].stock or 1)
 return row
end
P.weapon=group('weapon',40,'Weapons - full catalog',G.weapons)
P.gadget=group('gadget',220,'Gadgets and items - full catalog',G.gadgets)
local help=label(form,16,399,'Added equipment stays in inventory when this window closes.')
local memo=createMemo(form);P.memo=memo;memo.Left=12;memo.Top=425;memo.Width=710;memo.Height=195
memo.ReadOnly=true;memo.WordWrap=true;memo.ScrollBars='ssVertical';memo.Font.Name='Consolas';memo.Font.Size=10
function P.tick()
 if P.stopped then return end
 local ok,c=pcall(G.inspect);P.state=ok and c or nil
 for _,row in ipairs(rows)do
  local e=selected(row);local ready=ok and c.ready and e~=nil
  row.add.Enabled=not not ready;row.equip.Enabled=ready and e.equipable~=false or false
  row.unequip.Enabled=not not ready
  row.amount.Enabled=ready and (row.kind=='weapon'or e.kind~=nil)or false
  row.amountLabel.Caption=row.kind=='weapon'and 'Ammo stock'or e and e.kind=='level'and 'Card level'or e and e.kind=='timer'and 'Timer value'or 'Stock'
  if e then
   local raw=ok and (row.kind=='weapon'and c.h.ammo[e.id+1]or c.inventory[e.id])or nil
   local current=raw~=nil and raw~=0xFFFF and raw&gt;=0 and ((e.id==23 and row.kind=='gadget'and raw==0)and 'Attached to SOCOM'or tostring(raw&amp;0x7FFF))or 'Not owned'
   row.info.Caption='In inventory: '..current..'\r\n'..(e.note or (row.kind=='weapon'and 'Grant at least this stock; capacity is raised when needed.'or e.kind=='consumable'and 'Grant at least this stock; capacity is raised when needed.'or 'Adds this item to inventory.'))
  end
 end
 if not ok then memo.Lines.Text='Waiting for normal gameplay.\r\n'..errorText(c);return end
 local text={P.error and ('Action: '..P.error)or G.status,'',
  'Equipped weapon: '..displayName('weapon',c.activeWeapon),
  'Equipped gadget: '..displayName('gadget',c.activeGadget),
  'Area: '..c.stage..' | Inventory actions are one-shot.',
  'Health/no-alert toggles continue independently.','', 'Weapon inventory:'}
 for _,e in ipairs(G.weapons)do
  local n=c.h.ammo[e.id+1]
  text[#text+1]=string.format('  %-15s %s',e.name,n&lt;0 and 'Not owned'or (n..' / '..c.h.ammoMax[e.id+1]))
 end
 if G.logError then text[#text+1]='Action log: '..errorText(G.logError)end
 memo.Lines.Text=table.concat(text,'\r\n')
end
function P.stop(closing)
 if P.stopped then return true end;P.stopped=true
 if P.timer then P.timer.Enabled=false;P.timer.destroy();P.timer=nil end
 G.closeLog()
 if not closing then form.OnClose=nil;form.destroy()end
 if VRMInventoryPanel==P then VRMInventoryPanel=nil end
 local record=getAddressList().getMemoryRecordByID(305)
 if record and record.Description:match('^Weapon &amp; gadget selector')and record.Active then record.Active=false end
 return true
end
function P.show()form.show()end
form.OnClose=function()P.stop(true);return caFree end
local timer=createTimer(form,false);P.timer=timer;timer.Interval=250;timer.OnTimer=P.tick
VRMInventoryPanel=P;P.tick();timer.Enabled=true
return P
]====]):sub(2),
 [ [====[VR-Missions/vrm-discovery.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Read-only discovery of resident actor lists and relocated overlay parameters.
local D={version=1,root=nil}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xFFFFFFFF end
local function offset(p,n)
 assert(p and p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'Invalid PSX pointer')
 return p&amp;0x1FFFFF
end
local function header(ram,o)
 local b=assert(readBytes(ram+o,32,true),'Actor header unavailable')
 assert(#b==32,'Short actor header')
 local function w(i)return b[i+1]|(b[i+2]&lt;&lt;8)|(b[i+3]&lt;&lt;16)|(b[i+4]&lt;&lt;24)end
 return {offset=o,prev=w(0),next=w(4),act=w(8),die=w(12),namePointer=w(20)}
end
local function rootsValid(ram,root)
 if not root or root&lt;0x10000 or root+9*0x44&gt;0x200000 then return false end
 for i=0,8 do
  local s=header(ram,root+i*0x44);local e=header(ram,root+i*0x44+0x20)
  if s.prev~=0 or s.act~=0 or s.die~=0 or e.next~=0 or e.act~=0 or e.die~=0 then return false end
 end
 return true
end
function D.actorRoot(ram)
 if D.root and rootsValid(ram,D.root)then return D.root end
 local p=offset(u32(ram+0xac804),0x100)-0x20
 local seen={}
 for _=1,512 do
  assert(not seen[p],'Actor predecessor cycle');seen[p]=true
  local h=header(ram,p)
  if h.prev==0 then
   local roots={}
   for level=0,8 do local r=p-level*0x44;if rootsValid(ram,r)then roots[#roots+1]=r end end
   assert(#roots==1,'Actor-list root not uniquely identified');D.root=roots[1];return D.root
  end
  p=offset(h.prev,32)
 end
 error('Actor predecessor chain exceeds limit')
end
function D.actors(ram)
 local root=D.actorRoot(ram);local start=root+4*0x44;local finish=start+0x20
 local previous=start;local pointer=u32(ram+start+4);local result={};local seen={}
 for _=1,512 do
  local o=offset(pointer,32)
  if o==finish then
   assert(u32(ram+finish)==0x80000000+previous,'Actor tail changed during enumeration')
   return result
  end
  assert(not seen[o],'Actor-list cycle');seen[o]=true
  local h=header(ram,o)
  assert(h.prev==0x80000000+previous,'Actor list changed while reading')
  if h.act&gt;=0x800C0000 and h.act&lt;0x80200000 and h.die&gt;=0x800C0000 and h.die&lt;0x80200000 then
   local ok,n=pcall(function()return readString(ram+offset(h.namePointer,1),48)end)
   if ok and n then h.name=n;result[#result+1]=h end
  end
  previous=o;pointer=h.next
 end
 error('Actor count exceeds limit')
end
local function binary(ram,start,size)
 local parts={}
 for o=0,size-1,8192 do
  local n=math.min(8192,size-o);local b=assert(readBytes(ram+start+o,n,true),'Overlay read unavailable')
  assert(#b==n,'Short overlay read');parts[#parts+1]=string.char(table.unpack(b))
 end
 return table.concat(parts)
end
function D.overlay(ram)
 local code={start=0xC0000,size=0xA0000}
 code.bytes=binary(ram,code.start,code.size)
 function code.word(o)
  if o&lt;code.start or o+4&gt;code.start+code.size or o%4~=0 then return nil end
  return string.unpack('&lt;I4',code.bytes,o-code.start+1)
 end
 return code
end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function imm(w)local n=w&amp;0xFFFF;return n&gt;=32768 and n-65536 or n end
local function absolute(code,p,w)
 local base=rs(w)
 for back=1,3 do
  local h=code.word(p-back*4)
  if h and op(h)==15 and rt(h)==base then
   local a=((h&amp;0xFFFF)&lt;&lt;16)+imm(w)
   if a&gt;=0x800C0000 and a&lt;0x80200000 then return a&amp;0x1FFFFF end
  end
 end
end
local function guardGateProof(code)
 local found={}
 for p=code.start,code.start+code.size-12,4 do
  local w=code.word(p)
  if (op(w)==36 or op(w)==32)and (w&amp;0xFFFF)==0xBA3 then
   for j=1,2 do
    local a=code.word(p+4*j)
    if a and op(a)==12 and rs(a)==rt(w)then found[a&amp;0xFFFF]=true end
   end
  end
 end
 return found[1]and found[4]and found[16]
end
function D.reachable(code,entry)
 local pending={entry&amp;0x1FFFFF};local head=1;local seen={};local words={};local functions=0
 while head&lt;=#pending and functions&lt;180 do
  local fn=pending[head];head=head+1
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;functions=functions+1
   for p=fn,math.min(fn+0x2000,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if op(w)==3 then
     local target=((w&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if target&gt;=0x800C0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1FFFFF end
    end
    if w==0x03E00008 then words[p+4]=code.word(p+4);break end
   end
  end
 end
 return words
end
-- VR commander uses a materialized struct base, rather than absolute LHs.
function D.guardProfile(ram,actors,code)
 local watchers={}
 for _,a in ipairs(actors)do if a.name=='watcher.c'then watchers[a.offset]=a end end
 if not next(watchers)then return nil,'No standard guards loaded'end
 if not guardGateProof(code)then return nil,'Guard sensing layout not recognized'end
 local function s(n)return n&gt;=32768 and n-65536 or n end
 local function word(p)return code.word(p)end
 local function hi(w)return (w&amp;0xFFFF)&lt;&lt;16 end
 local matches={}
 for p=code.start,code.start+code.size-0x148,4 do
  local a,b,c,d,e,f,g,h,i,j,k=word(p),word(p+4),word(p+8),word(p+12),word(p+16),word(p+20),word(p+24),word(p+28),word(p+32),word(p+36),word(p+40)
  if a&amp;0xFFFF0000==0x3C020000 and b&amp;0xFFFF0000==0x24510000 and c&amp;0xFFFF0000==0x3C020000 and d==0x86230088 and e&amp;0xFFFF0000==0x3C040000 and f&amp;0xFFFF0000==0xAC430000 and g==0x8E020014 and h==0x246301F4 and i==0x284200FF and j&amp;0xFFFF0000==0x14400000 and k&amp;0xFFFF0000==0xAC830000 then
   local command=(hi(a)+s(b&amp;0xFFFF))&amp;0x1FFFFF
   local eye=(hi(c)+s(f&amp;0xFFFF))&amp;0x1FFFFF
   local shoot=(hi(e)+s(k&amp;0xFFFF))&amp;0x1FFFFF
   if command==eye+12 and shoot==eye-4 then
    local configs={}
    for q=p+44,p+0x148-16,4 do
     local load=word(q)
     if load==0x8623008A or load==0x8623008C then
      for z=q+4,q+16,4 do
       local store=word(z)
       if store==f then configs[load&amp;0xFFFF]=true end
      end
     end
    end
    local vision
    for _,actor in pairs(watchers)do
     for q in pairs(D.reachable(code,actor.act))do
      local w=word(q)
      if w==0x244207D0 and word(q+4)==0x0052102A then
       local load=word(q-8);local upper=word(q-12)
       if load and upper and load&amp;0xFFFF0000==0x8C420000 and upper&amp;0xFFFF0000==0x3C020000 and ((hi(upper)+s(load&amp;0xFFFF))&amp;0x1FFFFF)==eye then vision=q end
      end
     end
    end
    local count,mode=u32(ram+command+8),u32(ram+command+0x18)
    local matched=0
    if configs[0x8A]and configs[0x8C]and vision and count&lt;=8 and mode&lt;=2 then
     for slot=0,7 do
      local ptr=u32(ram+command+0xD4+slot*0x10)
      local actor=ptr&gt;=0x80000000 and ptr&lt;0x80200000 and watchers[ptr&amp;0x1FFFFF]
      if actor and readBytes(ram+actor.offset+0xB78,1)==slot then matched=matched+1 end
     end
     if matched&gt;0 then
      matches[#matches+1]={command=command,eye=eye,shoot=shoot,ranges=command+0x88,visionPC=vision,matched=matched,
       blocks={{offset=p,bytes=code.bytes:sub(p-code.start+1,p-code.start+0x148)}}}
     end
    end
   end
  end
 end
 if #matches~=1 then return nil,'VR guard commander mapping is not unique ('..#matches..')'end
 return matches[1]
end
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
function D.cameraProfile(actor,code)
 if not cameraNames[actor.name]then return nil end
 local pending={actor.act&amp;0x1FFFFF};local seen={};local candidates={};local examined=0
 while #pending&gt;0 and examined&lt;100 do
  local fn=table.remove(pending)
  if not seen[fn]and code.word(fn)then
   seen[fn]=true;examined=examined+1
   local words={};local workRegisters={}
   for p=fn,math.min(fn+0x1800,code.start+code.size-4),4 do
    local w=code.word(p);if not w then break end;words[p]=w
    if p&lt;fn+0x60 and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if (rs(w)==4 and rt(w)==0)or(rs(w)==0 and rt(w)==4)then workRegisters[rd(w)]=true end
    end
    if op(w)==3 then
     local target=((w&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if target&gt;=0x800C0000 and target&lt;0x80160000 then pending[#pending+1]=target&amp;0x1FFFFF end
    end
    if w==0x03E00008 then words[p+4]=code.word(p+4);break end
   end
   for p,w in pairs(words)do
    if op(w)==3 and (((w&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000)==0x80019ec0 then
     for j=1,7 do
      local compare=words[p+j*4]
      if compare and op(compare)==0 and (compare&amp;63)==42 and rt(compare)==2 then
       local rangeRegister=rs(compare)
       for back=p+j*4-4,math.max(fn,p-0x40),-4 do
        local load=words[back]
        if load and (op(load)==37 or op(load)==35)and rt(load)==rangeRegister and workRegisters[rs(load)]then
         local field=load&amp;0xFFFF;local size=op(load)==37 and 2 or 4
         if field&gt;=0x100 and field&lt;0x800 then
          local width=false
          for q,z in pairs(words)do if q&lt;p and op(z)==op(load)and rs(z)==rs(load)and (z&amp;0xFFFF)==field+size then width=true end end
          if width then candidates[field]={range=field,size=size,detector=fn,loadPC=back}end
         end
         break
        end
       end
      end
     end
    end
   end
  end
 end
 local profiles={};for _,v in pairs(candidates)do profiles[#profiles+1]=v end
 if #profiles~=1 then return nil,'Camera distance check is not unique ('..#profiles..')'end
 return profiles[1]
end
function D.guardActors(ram,actors,profile)
 local result={};if not profile then return result end
 local present={};for _,a in ipairs(actors)do present[a.offset]=a end
 for i=0,7 do
  local p=u32(ram+profile.command+0xC8+i*0x10+0xC)
  if p&gt;=0x80000000 and p&lt;0x80200000 then
   local a=present[p&amp;0x1FFFFF]
   if a and a.name=='watcher.c'and readBytes(ram+a.offset+0xB78,1)==i then a.slot=i;result[a.offset]=a end
  end
 end
 return result
end
return D
]====]):sub(2),
 [ [====[VR-Missions/vrm-guard-proximity.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- CE-side proximity modes for standard guards: knockout or kill.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if VRMGuardProximity and VRMGuardProximity.pid==getOpenedProcessID()and VRMGuardProximity.version==5 then return VRMGuardProximity end
if VRMGuardProximity then VRMGuardProximity.stop()end
local A=dofile(dir..'vrm-guard-state.lua')
local C={version=5,pid=A.pid,actions=A,enabled=false,mode=nil,radius=A.validateRadius(VRMProximityRadius or 3000),affected=0,batches=0,status='Proximity OFF'}
local ids={knockout=310,kill=311}
local prefixes={knockout='Proximity auto knockout',kill='Proximity auto kill'}
local function record(mode)
 local row=getAddressList().getMemoryRecordByID(ids[mode])
 return row and row.Description:find(prefixes[mode],1,true)==1 and row or nil
end
local function now()return getTickCount()end
function C.setRadius(value)
 C.radius=A.validateRadius(value);VRMProximityRadius=C.radius
 C.status=C.enabled and (C.mode..' ON | radius '..C.radius..' | waiting for nearby guards')or ('Proximity OFF | radius '..C.radius)
 return C.radius
end
function C.disable(mode)
 if mode and C.mode~=mode then return true end
 C.enabled=false;C.mode=nil
 if C.timer then C.timer.Enabled=false end
 C.state=nil;C.nextAction=nil;C.epoch=nil;C.nextCheck=nil
 C.status='Proximity OFF | radius '..C.radius
 for _,kind in ipairs({'knockout','kill'})do local row=record(kind);if row and row.Active then row.Active=false end end
 return true
end
local function audit(result)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/vrm-guard-proximity-actions.csv','a+'))
  local success,why=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Proximity action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,mode,radius,slot,actor,distance,hp_before,faint_before\n'))end
   for _,g in ipairs(result.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%d,%d,%08X,%.1f,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),C.pid,result.stage,result.mode,result.radius,g.actor.slot,0x80000000+g.actor.offset,g.distance,g.hp,g.faint)))end end
  end)
  f:close();assert(success,why)
 end)
 if not ok then C.logError=tostring(err)end
end
function C.tick()
 if not C.enabled or C.busy then return end
 if getOpenedProcessID()~=C.pid then C.disable();C.status='Stopped: process changed. Re-enable for the new process.';return end
 local time=now();if C.nextCheck and time&lt;C.nextCheck then return end
 C.busy=true
 local ok,err=pcall(function()
  local c=A.nearby(C.radius);C.state=c
  local epoch=c.ram..':'..c.stage
  if C.epoch~=epoch then C.epoch=epoch;C.nextAction=nil end
  C.status=string.format('%s ON | radius %d | %s | %d nearby, %d ready | %d affected',C.mode,C.radius,c.stage,c.inRange,c.nearEligible,C.affected)
  if c.nearEligible&gt;0 and (not C.nextAction or time&gt;=C.nextAction)then
   local result=A.apply(C.mode,{radius=C.radius})
   C.last=result;C.affected=C.affected+result.affected;C.batches=C.batches+1;C.nextAction=now()+1000
   C.status=string.format('%s ON | radius %d | %s | applied to %d guards (%d total)',C.mode,C.radius,result.stage,result.affected,C.affected)
   audit(result)
  end
 end)
 C.busy=false
 if not ok then
  -- Loading, menus, cutscenes, unsupported layouts or moving targets wait for
  -- a new valid context. No stale actor list is used and no dialog steals focus.
  C.state=nil;C.lastError=tostring(err);C.status='Waiting: '..C.lastError;C.nextCheck=now()+1000
 else C.lastError=nil;C.nextCheck=nil end
end
function C.enable(mode)
 assert(ids[mode],'Unknown proximity mode.')
 assert(not C.stopped and getOpenedProcessID()==C.pid,'Reopen proximity controls for this process.')
 if C.enabled and C.mode==mode then return true end
 C.disable();C.mode=mode;C.enabled=true;C.lastError=nil
 if not C.timer then C.timer=createTimer(nil,false);C.timer.Interval=500;C.timer.OnTimer=C.tick end
 -- Enabling the other AA entry must uncheck this entry without stopping the
 -- replacement mode. disable(mode) above is conditional on the current mode.
 C.status=mode..' ON | radius '..C.radius..' | checking every 500 ms'
 C.timer.Enabled=true
 return true
end
function C.stop()
 C.disable();C.stopped=true
 if C.timer then C.timer.destroy();C.timer=nil end
 if VRMGuardProximity==C then VRMGuardProximity=nil end
 return true
end
VRMGuardProximity=C
return C
]====]):sub(2),
 [ [====[VR-Missions/vrm-guard-state.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Optional one-shot outcomes for standard watcher.c guards. No injected calls.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=VRMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'vrm-reader.lua')end
local D=dofile(dir..'vrm-discovery.lua')
local B=dofile(dir..'vrm-ownership.lua')
local A={version=2,pid=R.pid,status='Choose a one-shot guard action.'}
local nativeCache
local function u16(a)return assert(readSmallInteger(a),'Guard short unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Guard word unavailable')&amp;0xFFFFFFFF end
local function bytes(a,n)
 local out={};for j=0,n-1,4096 do
  local k=math.min(4096,n-j);local b=assert(readBytes(a+j,k,true),'Guard code unavailable');assert(#b==k)
  out[#out+1]=string.char(table.unpack(b))
 end;return table.concat(out)
end
local function hex(s)return s:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function context()
 assert(getOpenedProcessID()==A.pid,'Attached process changed; reopen the guard panel.')
 local h=R.read();local r=h.ram
 assert(h.health&gt;0 and u32(r+0xac1e8)==0 and u32(r+0xac848)~=0 and u32(r+0xac1ec)==0,'Wait for living, normal gameplay.')
 assert(u32(r+0xac1e4)&amp;0xD40C0000==0 and u32(r+0xac860)&amp;0x20002084==0,'Finish the scene or restricted action first.')
 local control=u32(r+0xac804)
 assert(control&gt;=0x80000020 and control&lt;0x801FF000,'Normal Snake is not loaded.')
 local snake=(control&amp;0x1FFFFF)-0x20
 assert(u32(r+snake+8)==0x8005d5ac and u32(r+snake+12)==0x8005dc00 and u32(r+0xac830)==0x80000000+snake+0x9C,'Snake actor differs.')
 assert(u32(r+0xbe4f0+8)==0x8003b864 and u32(r+0xbe4f0+12)==0x8003b9a8 and u16(r+0xbe4f0+0x2A)==0,'Close the game menu first.')
 local stage=assert(readString(r+0xb5b98,16))
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Area is not ready.')
 return {ram=r,stage=stage,h=h,snake=snake}
end
local function damageProfile(code)
 local header=hex('E0FFBD271000B0AF218080001800BFAF1400B1AF0009118E0000000006002296')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'VR guard damage handler is missing or ambiguous')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'VR guard damage branches differ')end
 match(0x20,'000000000400423067004010211000003E00229600000000FFFF422400140200031C02000900622C5C004010')
 match(0x54,'80180300211862000000628C000000000800400000000000')
 local upper,lower=code.word(fn+0x4C),code.word(fn+0x50)
 assert(upper&amp;0xFFFF0000==0x3C020000 and lower&amp;0xFFFF0000==0x24420000,'VR guard switch layout differs')
 local tablePSX=((upper&amp;0xFFFF)&lt;&lt;16)+signed(lower&amp;0xFFFF)
 assert(tablePSX&gt;=0x800C0000 and tablePSX+36&lt;=0x80160000,'VR damage switch outside overlay')
 local t=tablePSX&amp;0x1FFFFF
 assert(code.word(t)==0x80000000+fn+0xE4 and code.word(t+8)==0x80000000+fn+0x6C,'VR lethal/stun mode routing differs')
 match(0x94,'2A002286000000000700401C9C0004262128000001000224DC0802AE')
 match(0x10C,'26002286000000000700401C9C0004262128000001000224DC0802AE')
 match(0x1A8,'EC0802AEF40800AE700000A6')
 match(0x1C0,'280020A6060020A6')
 return {fn=fn,tableOffset=t,code=code.bytes:sub(start,start+0x1DC-1),switch=code.bytes:sub(t-code.start+1,t-code.start+36)}
end
local function recoveryProfile(code)
 local header=hex('D8FFBD271800B0AF218080002000BFAF1C00B1AF700B028E2188A00020004234')
 local start=code.bytes:find(header,1,true)
 assert(start and not code.bytes:find(header,start+1,true),'Guard knockout recovery handler differs.')
 local fn=code.start+start-1
 local function match(o,s)assert(code.bytes:sub(start+o,start+o+#hex(s)-1)==hex(s),'Guard knockout timer layout differs.')end
 match(0x1CC,'5A0B02A6')
 match(0x1F0,'5A0B0286000000002A1051001200401000000000')
 match(0x204,'0009038E000000002A006284000000000400401C9C000426840B0296000000002A0062A4')
 return {fn=fn,code=code.bytes:sub(start,start+0x25C-1)}
end
function A.inspect(useCache)
 local c=context();local r=c.ram
 local actors=D.actors(r)
 c.guards={};c.eligible=0;c.knockedOut=0;c.dead=0;c.skipped=0;c.total=0
 local identity={};local watchers=0
 for _,a in ipairs(actors)do if a.name=='watcher.c'or a.name=='command.c'then
  identity[#identity+1]=a.name..':'..a.offset..':'..a.act..':'..a.die..':'..bytes(r+(a.act&amp;0x1FFFFF),32)
  if a.name=='watcher.c'then watchers=watchers+1 end
 end end
 if watchers==0 then nativeCache=nil;c.reason='No standard guards loaded';return c end
 table.sort(identity);local key=r..':'..c.stage..':'..table.concat(identity,'|')
 local cached=useCache and nativeCache and nativeCache.key==key and nativeCache or nil
 if cached and bytes(cached.proof.address,32)~=cached.proof.bytes then cached=nil end
 local code=cached and cached.code or D.overlay(r)
 local profile,why
 if cached then profile=cached.profile else profile,why=D.guardProfile(r,actors,code)end
 if not profile then c.reason=why;return c end
 c.profile=profile;c.damage=cached and cached.damage or damageProfile(code);c.recovery=cached and cached.recovery or recoveryProfile(code);c.ownership={}
 c.profileProof={address=r+profile.visionPC-12,bytes=bytes(r+profile.visionPC-12,32)}
 local families=cached and cached.families or {};local reachable=cached and cached.reachable or {};local retained={};local targets={}
 for _,actor in pairs(D.guardActors(r,actors,profile))do
  local w=actor.offset
  assert(actor.name=='watcher.c'and w~=c.snake and w&gt;=0x10000 and w+0xC4C&lt;=0x200000,'Guard ownership differs.')
  local family=actor.act..':'..actor.die;local e=families[family]
  if not e then e=B.ownership(r,actor);assert(e.targets[0x900],'Guard TARGET pointer lacks native ownership proof.');families[family]=e end
  if not retained[family]then c.ownership[#c.ownership+1]=e;retained[family]=true end
  local ptr=u32(r+w+0x900)
  assert(ptr&gt;=0x800b72f0 and ptr&lt;0x800b84f0 and (ptr-0x800b72f0)%0x48==0,'Guard target pool slot differs.')
  assert(not targets[ptr],'Two guards share a damage target.');targets[ptr]=true
  local t=r+(ptr&amp;0x1FFFFF);local hp,faint=u16(t+0x26),u16(t+0x2A)
  assert(u16(t+2)==2,'Guard target is not enemy-owned.')
  local g={actor=actor,pointer=ptr,target=t,hp=hp,faint=faint,class=u16(t),flags=u16(t+6),action=u32(r+w+0x8EC),status=u32(r+w+0xB70)}
  c.total=c.total+1
  if hp==0 or hp&gt;=32768 then g.reason='dead';c.dead=c.dead+1
  elseif faint==0 or faint&gt;=32768 then g.reason='knocked out / recovering';c.knockedOut=c.knockedOut+1
  elseif g.class&amp;4==0 or g.flags&amp;6~=0 or u16(t+0x42)~=0 or u16(r+w+0xC2C)~=0 then g.reason='busy / not accepting damage';c.skipped=c.skipped+1
  else
   local accepts=reachable[g.action]
   if accepts==nil then accepts=g.action&gt;=0x800C0000 and g.action&lt;0x80160000 and D.reachable(code,g.action)[c.damage.fn]~=nil;reachable[g.action]=accepts end
   if accepts then g.eligible=true;c.eligible=c.eligible+1
   else g.reason='current action has no verified damage path';c.skipped=c.skipped+1 end
  end
  c.guards[#c.guards+1]=g
 end
 table.sort(c.guards,function(a,b)return a.actor.slot&lt;b.actor.slot end)
 nativeCache={key=key,code=code,profile=profile,damage=c.damage,recovery=c.recovery,proof=c.profileProof,families=families,reachable=reachable}
 return c
end
function A.validateRadius(radius)
 radius=tonumber(radius)
 assert(radius and radius==math.floor(radius)and radius&gt;=100 and radius&lt;=20000,'Radius must be a whole number from 100 to 20000 game units.')
 return radius
end
local function distance(r,snake,actor)
 local squared=0
 for i=0,2 do
  local delta=signed(u16(r+snake+0x20+i*2))-signed(u16(r+actor+0x20+i*2))
  squared=squared+delta*delta
 end
 return math.sqrt(squared)
end
function A.nearby(radius)
 radius=A.validateRadius(radius)
 -- Cached scans only nominate candidates. A.apply always rediscovers native
 -- evidence from current RAM and checks range again before any target write.
 local c=A.inspect(true);c.radius=radius;c.inRange=0;c.nearEligible=0
 for _,g in ipairs(c.guards)do
  g.distance=distance(c.ram,c.snake,g.actor.offset);g.inRange=g.distance&lt;=radius
  if g.inRange then c.inRange=c.inRange+1;if g.eligible then c.nearEligible=c.nearEligible+1 end end
 end
 return c
end
function A.apply(mode,options)
 assert(mode=='kill'or mode=='knockout','Choose kill or knockout.')
 options=options or {};local radius=options.radius and A.validateRadius(options.radius)or nil
 local c=A.inspect()
 if radius then
  c.eligible=0
  for _,g in ipairs(c.guards)do if g.eligible then
   g.distance=distance(c.ram,c.snake,g.actor.offset)
   if g.distance&lt;=radius then c.eligible=c.eligible+1 else g.eligible=false;g.reason='outside proximity radius'end
  end end
 end
 assert(c.eligible&gt;0,'No eligible standard guards. '..(c.reason or 'Already down, busy, outside radius, or unsupported.'))
 local writes,notifications={},{}
 local function plan(a,v,label)
  writes[#writes+1]={address=a,before=u16(a),value=v,label=label}
 end
 for _,g in ipairs(c.guards)do if g.eligible then
  local t=g.target
  plan(t+0x3E,mode=='kill'and 1 or 3,'damage mode')
  if mode=='kill'then plan(t+0x26,0,'vital')else plan(t+0x2A,0,'faint')end
  plan(t+0x28,mode=='kill'and g.hp or 0,'damage amount')
  for _,o in ipairs({0x2C,0x2E,0x30})do plan(t+o,0,'impact force')end
  notifications[#notifications+1]={address=t+6,before=g.flags,value=g.flags|4,label='damage notification'}
 end end
 -- Validate the whole batch before any writes; never reuse a previous area.
 local fresh=context();assert(fresh.ram==c.ram and fresh.stage==c.stage and fresh.snake==c.snake,'Area/player changed; refresh.')
 assert(bytes(c.ram+c.damage.fn,#c.damage.code)==c.damage.code and bytes(c.ram+c.damage.tableOffset,36)==c.damage.switch,'Guard damage code changed.')
 assert(bytes(c.profileProof.address,32)==c.profileProof.bytes,'Guard commander binding changed.')
 for _,block in ipairs(c.profile.blocks or {})do assert(bytes(c.ram+block.offset,#block.bytes)==block.bytes,'VR commander code changed.')end
 for _,e in ipairs(c.ownership)do for _,p in ipairs(e.blocks)do assert(bytes(p.address,#p.bytes)==p.bytes,'Guard native ownership code changed.')end end
 for _,g in ipairs(c.guards)do if g.eligible then
  local a,t=g.actor,g.target;local w=c.ram+a.offset
  assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+20)==a.namePointer and readString(c.ram+(a.namePointer&amp;0x1FFFFF),48)=='watcher.c','Guard actor changed.')
  assert(u32(c.ram+c.profile.command+0xC8+a.slot*0x10+0xC)==0x80000000+a.offset and readBytes(w+0xB78,1)==a.slot,'Commander no longer owns guard.')
  assert(u32(w+0x900)==g.pointer and u32(w+0x8EC)==g.action,'Guard target/action changed; retry.')
  assert(u16(t)==g.class and u16(t+2)==2 and u16(t+0x26)==g.hp and u16(t+0x2A)==g.faint and u16(t+0x42)==0 and u16(w+0xC2C)==0,'Guard damage state changed; retry.')
  if radius then assert(distance(c.ram,c.snake,a.offset)&lt;=radius,'Guard moved outside the proximity radius; retry.')end
 end end
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do assert(u16(v.address)==v.before,'Guard state changed; retry.')end end
 local count=0
 for _,list in ipairs({writes,notifications})do for _,v in ipairs(list)do
  assert(writeSmallInteger(v.address,v.value),'Guard write failed after '..count..' writes.');count=count+1
 end end
 A.last={mode=mode,pid=A.pid,ram=c.ram,stage=c.stage,affected=c.eligible,skipped=c.total-c.eligible,writes=count,guards=c.guards,recovery=c.recovery,command=c.profile.command,radius=radius}
 A.status=string.format('%s requested for %d guards; %d skipped. Resume gameplay.',mode,c.eligible,c.total-c.eligible)
 local ok,err=pcall(function()
  local f=assert(io.open(dir..'../../logs/vrm-guard-state-actions.csv','a+'))
  local success,problem=pcall(function()
   assert(f:seek('end')&lt;10*1024*1024,'Guard action log reached 10 MiB.')
   if f:seek('end')==0 then assert(f:write('utc,pid,area,action,guard,target,hp_before,faint_before\n'))end
   for _,g in ipairs(c.guards)do if g.eligible then assert(f:write(string.format('%s,%d,%s,%s,%08X,%08X,%d,%d\n',os.date('!%Y-%m-%dT%H:%M:%SZ'),A.pid,c.stage,mode,0x80000000+g.actor.offset,g.pointer,g.hp,g.faint)))end end
  end)
  f:close();assert(success,problem)
 end)
 if not ok then A.logError=tostring(err)end
 VRMGuardState=A;return A.last
end
function A.extendKnockout(result,ticks)
 assert(result==A.last and result.mode=='knockout','A fresh knockout result is required.')
 assert(type(ticks)=='number'and ticks==math.floor(ticks)and ticks&gt;=30 and ticks&lt;=10000,'Invalid recovery delay.')
 if A.extension then A.extension.stop()end
 local T={extended=0,stopped=false,remaining={},writes={}};A.extension=T
 for _,g in ipairs(result.guards)do if g.eligible then T.remaining[#T.remaining+1]=g end end
 local start=getTickCount();local timer=createTimer(nil,false);timer.Interval=100;T.timer=timer
 function T.stop()if not T.stopped then T.stopped=true;timer.Enabled=false;timer.destroy()end end
 function T.tick()
  if T.stopped then return end
  local ok,err=pcall(function()
   local c=context();assert(c.ram==result.ram and c.stage==result.stage,'Area changed; recovery extension cancelled.')
   local r=c.ram;assert(bytes(r+result.recovery.fn,#result.recovery.code)==result.recovery.code,'Recovery code changed.')
   for i=#T.remaining,1,-1 do
    local g=T.remaining[i];local a=g.actor;local w=r+a.offset
    assert(u32(w+8)==a.act and u32(w+12)==a.die and u32(w+0x900)==g.pointer,'Guard owner changed.')
    assert(u32(r+result.command+0xC8+a.slot*0x10+0xC)==0x80000000+a.offset and readBytes(w+0xB78,1)==a.slot,'Guard commander changed.')
    assert(u16(g.target+2)==2 and u16(g.target+0x26)==g.hp,'Guard health/side changed.')
    local time=u32(w+0x8F4)
    if u32(w+0x8EC)==0x80000000+result.recovery.fn and time&gt;=1 and time&lt;32767-ticks and u16(g.target+0x2A)==0 and u16(g.target+0x42)==0 and u32(w+0xB70)&amp;0x20~=0 then
     local old=u16(w+0xB5A);assert(old&lt;32768,'Recovery threshold differs.')
     local value=math.max(old,time+ticks)
     assert(writeSmallInteger(w+0xB5A,value),'Recovery delay write failed.')
     T.writes[#T.writes+1]={actor=a.offset,before=old,after=value};T.extended=T.extended+1;table.remove(T.remaining,i)
    end
   end
   if #T.remaining==0 then A.status='Extended knockout applied to '..T.extended..' guards; they will recover normally.';T.stop()end
  end)
  if not ok then T.error=tostring(err);A.status='Recovery extension stopped: '..T.error;T.stop()
  elseif getTickCount()-start&gt;=15000 then T.error='Timed out waiting for guards to reach the floor.';A.status=T.error;T.stop()end
 end
 timer.OnTimer=T.tick;timer.Enabled=true
 A.status='Knockout requested; waiting to extend the normal recovery timers.'
 return T
end
VRMGuardState=A
return A
]====]):sub(2),
 [ [====[VR-Missions/vrm-inventory.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- One-shot inventory grants and normal game equipment-selection requests.
-- All weapon/item slots are selectable, including equipment not yet owned.
if VRMInventory and VRMInventory.pid==getOpenedProcessID()then return VRMInventory end
if VRMInventory and VRMInventory.closeLog then VRMInventory.closeLog()end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=VRMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'vrm-reader.lua')end
local G={pid=R.pid,reader=R,version=1,pending={},status='Choose equipment to add to inventory.'}
G.weapons={
 {id=0,name='SOCOM',stock=25},{id=1,name='FAMAS',stock=100},
 {id=2,name='Grenade',stock=8},{id=3,name='Nikita',stock=10},
 {id=4,name='Stinger',stock=10},{id=5,name='Claymore',stock=8},
 {id=6,name='C4',stock=8},{id=7,name='Stun grenade',stock=8},
 {id=8,name='Chaff grenade',stock=8},{id=9,name='PSG1',stock=10},
}
G.gadgets={
 {id=0,name='Cigarettes'},{id=1,name='Binoculars'},
 {id=2,name='Cardboard box A'},{id=3,name='Cardboard box B'},{id=4,name='Cardboard box C'},
 {id=5,name='Night-vision goggles'},{id=6,name='Thermal goggles'},
 {id=7,name='Gas mask'},{id=8,name='Body armor'},{id=9,name='Ketchup'},
 {id=10,name='Stealth camouflage'},{id=11,name='Bandana'},{id=12,name='Camera'},
 {id=13,name='Rations',kind='consumable',stock=5},
 {id=14,name='Cold medicine',kind='consumable',stock=5},
 {id=15,name='Diazepam',kind='consumable',stock=5},
 {id=16,name='PAL key',note='Adds the PAL key. Its temperature/state stays under game control.'},
 {id=17,name='Key card',kind='level',stock=7,note='Choose an access level from 1 to 7.'},
 {id=18,name='Time bomb (story countdown)',kind='timer',stock=30000,equipable=false,
  note='Story time-bomb value. Adding it can start a countdown; the value uses game timer units.'},
 {id=19,name='Mine detector'},{id=20,name='MO disk'},{id=21,name='Rope'},
 {id=22,name='Handkerchief'},
 {id=23,name='SOCOM suppressor',equipable=false,note='Adds the suppressor. SOCOM attaches it through the normal weapon update.'},
}
local function u16(a)return assert(readSmallInteger(a),'Inventory read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Game state unavailable')&amp;0xFFFFFFFF end
local function signed32(v)return v&gt;=0x80000000 and v-0x100000000 or v end
local function owned(raw)return raw~=0xFFFF end
local function amount(raw)return owned(raw)and (raw&amp;0x7FFF)or 0 end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xFFFF),'Inventory write failed')end
local function fingerprint(a,expected)
 local b=assert(readBytes(a,#expected,true),'Equipment-switch code unavailable')
 for i,v in ipairs(expected)do assert(b[i]==v,'Equipment-switch layout differs')end
end
local function entry(kind,id)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Select valid equipment')
 local list=kind=='weapon'and G.weapons or G.gadgets
 local e=list[id+1];assert(e and e.id==id,'Equipment ID out of range')
 return e
end
function G.context(writing)
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xac1e8)==0 and u32(ram+0xac848)~=0,'Wait for area loading to finish.')
 local control=u32(ram+0xac804)
 assert(control&gt;=0x80000020 and control&lt;0x80200000,'Snake is not ready.')
 local work=(control&amp;0x1FFFFF)-0x20
 assert(work+0xA24&lt;0x200000,'Snake actor bounds differ.')
 assert(u32(ram+work+8)==0x8005d5ac and u32(ram+work+12)==0x8005dc00,'Wait for normal gameplay.')
 assert(u32(ram+0xac830)==0x80000000+work+0x9C,'Snake body ownership differs.')
 local flags=u32(ram+0xac1e4);local player=u32(ram+0xac860)
 local ready=h.health&gt;0 and u32(ram+0xac1ec)==0 and flags&amp;0xD40C0000==0 and player&amp;0x20002084==0
 if writing then assert(ready,'Finish the cutscene or restricted action first.')end
 return {h=h,ram=ram,work=work,ready=ready,frame=u32(ram+0xac7f8),
  activeWeapon=signed32(u32(ram+work+0x918)),activeGadget=signed32(u32(ram+work+0x9A4)),
  stage=readString(ram+0xb5b98,16)or '?'}
end
local function log(kind,e,requested,actual,equipping,c)
 local ok,err=pcall(function()
  if not G.log then
   G.logPath=dir..'../../logs/vrm-inventory-actions-'..G.pid..'.csv'
   G.log=assert(io.open(G.logPath,'a'))
   if G.log:seek()==0 then G.log:write('utc,stage,category,id,name,requested,actual,equip\n')end
  end
  local name='"'..e.name:gsub('"','""')..'"'
  assert(G.log:write(table.concat({os.date('!%Y-%m-%dT%H:%M:%SZ'),c.stage,kind,e.id,name,requested,actual,equipping and 1 or 0},',')..'\n'))
  G.log:flush()
 end)
 if not ok then G.logError=tostring(err)end
end
function G.closeLog()
 if G.log then G.log:close();G.log=nil end
end
function G.equip(kind,id,c)
 assert(kind=='weapon'or kind=='gadget','Unknown equipment category')
 assert(type(id)=='number'and id==math.floor(id),'Equipment ID must be an integer')
 local e=id==-1 and {id=-1,name='Nothing'}or entry(kind,id)
 assert(e.equipable~=false,'Add this item to inventory; it is not directly equipped.')
 c=c or G.context(true)
 R.checkFeature('inventory')
 local address=kind=='weapon'and 0xb5bca or 0xb5bf2
 if id&gt;=0 then assert(owned(u16(c.ram+address+id*2)),'Add the selected equipment first.')end
 -- These are the same requested slots used by the normal inventory menu.
 -- The game creates/removes equipment actors and updates its active caches.
 local slot=kind=='weapon'and 0xb5bc4 or 0xb5bc6
 put16(c.ram+slot,id)
 G.pending[kind]={id=id,name=e.name,ram=c.ram,work=c.work,frame=c.frame}
 G.status=e.name..' selected. Resume gameplay to finish equipping.'
 return true
end
function G.grant(kind,id,quantity,equipping)
 local e=entry(kind,id)
 assert(not equipping or e.equipable~=false,'This item is added to inventory without equipping.')
 quantity=tonumber(quantity or e.stock or 1)
 local maximum=kind=='weapon'and 9999 or e.kind=='level'and 7 or e.kind=='timer'and 32767 or e.kind=='consumable'and 9999 or 1
 assert(quantity and quantity==math.floor(quantity)and quantity&gt;=1 and quantity&lt;=maximum,'Amount must be a whole number from 1 to '..maximum..'.')
 local c=G.context(true)
 R.checkFeature('inventory')
 local base=kind=='weapon'and 0xb5bca or 0xb5bf2
 local address=c.ram+base+id*2;local raw=u16(address)
 local value=(kind=='weapon'or e.kind)and math.max(amount(raw),quantity)or 1
 assert(value&lt;32768,'Existing inventory count is invalid.')
 local capacity
 if kind=='weapon'then capacity=c.ram+0xb5bde+id*2
 elseif e.kind=='consumable'then capacity=c.ram+0xb5bf2+(id+11)*2 end
 if capacity then
  local old=u16(capacity);if old&gt;=32768 then old=0 end
  if old&lt;value then put16(capacity,value)end
 end
 put16(address,value)
 local actual=u16(address)
 assert(owned(actual),'Game did not retain the inventory entry.')
 G.status=e.name..' added to inventory.'
 if equipping then G.equip(kind,id,c)end
 log(kind,e,quantity,actual,equipping,c)
 return {id=id,name=e.name,value=actual,capacity=capacity and u16(capacity)or nil,equipping=not not equipping}
end
function G.inspect()
 local c=G.context(false);c.inventory={}
 for _,e in ipairs(G.gadgets)do c.inventory[e.id]=u16(c.ram+0xb5bf2+e.id*2)end
 for kind,p in pairs(G.pending)do
  local actual=kind=='weapon'and c.activeWeapon or c.activeGadget
  local requested=kind=='weapon'and c.h.weapon or c.h.item
  if actual==p.id then
   G.status=p.name..' equipped.';G.pending[kind]=nil
  elseif c.ram~=p.ram or c.work~=p.work then
   G.status=p.name..' was added; the area changed before equipment was confirmed.';G.pending[kind]=nil
  elseif c.frame-p.frame&gt;180 and requested~=p.id then
   G.status=p.name..' is in inventory. The game selected different equipment.';G.pending[kind]=nil
  end
 end
 return c
end
G.entry=entry;G.owned=owned;G.amount=amount
VRMInventory=G
return G
]====]):sub(2),
 [ [====[VR-Missions/vrm-mission-clear-proofs.lua]====] ]=([====[!-- Captured vr_scm03 native clear transition, dispatch and message receiver.
return {
 {offset=0xD87B8,hex='212880000e80033c020002240b80043c705f62ace4c1828c0010033c25104300e4c182ac0b01a2900000000002004014010042240b01a2a00800e00300000000'},
 {offset=0xD9394,hex='e8ffbd271000b0af218080001400bfaf0b010392000000000800622c470040100e80023cc455422480180300211862000000628c0000000008004000000000001801028e0000000082100200010042300c0040100b80023ca85b44241e008284ffff032402004310000000001e0083a41c0082840000000002004310000000001c0083a43862030c000000000b80043c60c8828c0020033c251043003065030860c882ac0b01029200000000010042240e62030c0b0102a234650308000000000b80023ca85b44241600828400000000160040180e80023c705f438c050002241200621002000224200083840000000003006210000000000e62030c000000003a64030c2120000230650308000000000b80023cc85b43840200022403006210000000000e62030c000000000b01029200000000010042240b0102a21400bf8f1000b08f0800e0031800bd27'},
 {offset=0xD9888,hex='d0ffbd272000b0af21808000c800042421288000213080002800bfaf43ef000c2400b1af1801028e0000000001004230e80040140e80113c'},
 {offset=0xD9F84,hex='be5b4284000000000500401c000000001801028e0000000002004234180102ae1801028e0000000042100200010042300b004014000000006e65030c21200002e564030c212000021801028e00000000421002000100423003004010000000004f65030c21200002e163030c212000022800bf8f2400b18f2000b08f0800e0033000bd27'},
 {offset=0xD9800,hex='4267000c00568424080002160e80043c705f828e000000000400531400000000ee61030c212020020e80043c'},
 {offset=0xDD51C,hex='c8ffbd272000b2af219080003000bfaf2c00b5af2800b4af2400b3af1c00b1af1800b0af2800448e7a65000c1000a527218840001400201aafed15340e80143c010013241000a38f0000000004006294000000000d005510afed0234040070944267000c845884260200021600000000ae0353a21000a28fffff312614004224f0ff201e1000a2af211000003000bf8f2c00b58f2800b48f2400b38f2000b28f1c00b18f1800b08f0800e0033800bd27'},
 {offset=0xDE050,hex='e8ffbd271000b0af218080001400bfafae03039201000224120062100200622805004010000000000800601000000000427803080000000002000224100062100000000042780308000000004771030c212000024775030c212000024278030800000000d876030c21200002ae030292000000000100422442780308ae0302a2f875030c21200002b403038e00000000090060100c00022406006214010062240b80033c81000224e8c162ac42780308b40300aeb40302ae1400bf8f1000b08f0800e0031800bd270800e00300000000'},
 {offset=0xD90E8,hex='c0ffbd273800b0af218080000e80023c3c00bfafb8554c24030089890000899907008a8904008a9908008b812b00a9ab2800a9bb2f00aaab2c00aabb3000aba309008981000000003100a9a30b80023c04c8438c40000296000000004e0062a40b80023ca85b432422006284340007860b0041042130000021206000220003240b00c2280600401002006324211064000000428400000000f9ff40040100c6240a0103920500022408006214040002240e80033c585f628c0000000010004234585f62ac0a01039204000224070062140a00c2280e80023c585f438cefff04242418640085640308585f43ac0f0040100b80033ca85b63241100c22440100200211043002120a603000043842800829000000000180062001401028e121800002338e30021104300140102ae0a01039202000224120062140e80023c505f438c0000000006006010000000000100022407006210000000009a640308000000001401028ea6ffe724996403085a0042241401028ee2ffe7241e004224140102ae0200e1040e80023c21380000685f428c000000000200410400000000231002002a10e2000300401402000624ba640308030006241200c0100e80033c605f632480200600ffffc62480100600211043000000458c21208300000085ac0000428c000000000200410400000000231002002a10e200efff4014000000000100c6240300c22c050040100e80033c605f63248010060021104300000047ac040002241000a2a71800a2270e80043c605f83240e80053c1400a2af34000886585fa28c403006000c0067ac605f848c0400678c0800638c25104600585fa2ac1800a8af1c00a4af2000a7af2400a3af1801028e3800038e0800423406006010180102aefe61030c000000003800048e498c000c1000a527380000ae080100a23c00bf8f3800b08f0800e0034000bd27'},
 {offset=0x23078,hex='212880000b80043c284a838ce8ffbd271000bfaf0000628c000000000f00401000000000284a842400006294000000000500451400000000020063940400828c398c000821104300040063240000628c00000000f4ff4014000000000180043c3c32020c44028424211000001000bf8f000000000800e0031800bd27'},
 {offset=0x23124,hex='e8ffbd270b80023ce8c1428c211880001000b0af2180a000070040141400bfaf0b80023c60c8428c000000000020423007004010000000000180043c580284243c32020c21286000628c0008211000001e8c000c2120600003004424c48c000c212800021400bf8f1000b08f0800e0031800bd27'},
}
]====]):sub(2),
 [ [====[VR-Missions/vrm-mission-clear.lua]====] ]=([====[!-- One-shot normal mission clear for verified US VR native layouts.
-- No code patch, injected call, timer/score edit or direct completion-table write.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local root=dir
local G=dofile(root..'vrm-inventory.lua')
local proofs=dofile(dir..'vrm-mission-clear-proofs.lua')
local M={pid=G.pid,version=2}
local function u32(a)return assert(readInteger(a),'Clear state unavailable')&amp;0xFFFFFFFF end
local function byte(a)return assert(readBytes(a,1),'Clear byte unavailable')end
local function procedure(r,id)
 assert(id&gt;0 and id&lt;=0xFFFF,'Invalid live clear procedure ID')
 -- Mirror the native GCL procedure lookup at 80023078, without executing it.
 local tablePSX,basePSX=u32(r+0xB4A28),u32(r+0xB4A2C)
 assert(tablePSX&gt;=0x80010000 and tablePSX&lt;0x801FFFF8 and tablePSX%4==0,'Script procedure table invalid')
 assert(basePSX&gt;tablePSX and basePSX&lt;0x80200000,'Script procedure base invalid')
 local t,b=tablePSX&amp;0x1FFFFF,basePSX&amp;0x1FFFFF
 local found,ended
 for i=0,1023 do
  assert(t+i*4+4&lt;=0x200000,'Script table exceeds guest RAM')
  local entry=u32(r+t+i*4)
  if entry==0 then
   assert(b==t+(i+1)*4,'Script table/base binding differs');ended=true;break
  end
  if entry&amp;0xFFFF==id then assert(not found,'Ambiguous clear procedure');found=b+(entry&gt;&gt;16)end
 end
 assert(ended and found and found+3&lt;0x200000,'Live clear procedure not found')
 assert(byte(r+found)==0x40,'Clear procedure header differs')
 local size=byte(r+found+1)*256+byte(r+found+2)
 assert(size&gt;=3 and found+size&lt;=0x200000,'Clear procedure length invalid')
 local body={};for _,v in ipairs(assert(readBytes(r+found,size,true)))do body[#body+1]=string.char(v)end
 assert(#body==size,'Short clear procedure read')
 return found,table.concat(body)
end
local function code(r)
 for _,p in ipairs(proofs)do
  local expected={};for v in p.hex:gmatch('%x%x')do expected[#expected+1]=tonumber(v,16)end
  local actual=assert(readBytes(r+p.offset,#expected,true),'Clear code unavailable')
  assert(#actual==#expected,'Short clear code read')
  for i,v in ipairs(expected)do assert(actual[i]==v,'Mission-clear native code differs')end
 end
end
local function actor(r,level,name,act,die)
 local start=0xADA28+level*0x44;local finish=start+0x20
 local previous=start;local p=u32(r+start+4);local seen={};local found
 for _=1,256 do
  assert(p&gt;=0x80010000 and p&lt;=0x801FFC00,'Actor bounds differ')
  local o=p&amp;0x1FFFFF
  assert(u32(r+o)==0x80000000+previous,'Actor list changed')
  if o==finish then assert(found,'Mission actor missing: '..name);return found end
  assert(not seen[o],'Actor list cycle');seen[o]=true
  if u32(r+o+8)==act and u32(r+o+12)==die then
   local n=u32(r+o+20);assert(n&gt;=0x80010000 and n&lt;0x80200000,'Actor name invalid')
   if readString(r+(n&amp;0x1FFFFF),48)==name then assert(not found,'Ambiguous mission actor');found=o end
  end
  previous=o;p=u32(r+o+4)
 end
 error('Actor traversal exceeded bound')
end
function M.inspect()
 assert(getOpenedProcessID()==M.pid,'Attached process changed')
 local c=G.context(true);local r=c.ram
 assert(c.stage:match('^vr_[%w_]+$'),'Enter a playable VR mission')
 assert((readSmallInteger(r+0xBE4F0+0x2A)&amp;0xFFFF)==0,'Close the game menu')
 code(r)
 c.vr=actor(r,5,'vr.c',0x800D9888,0x800DA008)
 c.results=actor(r,7,'vrclear.c',0x800DE050,0x800DE118)
 c.mode=u32(r+0xE5F70);c.sequence=byte(r+c.vr+0x10B)
 c.resultPhase=byte(r+c.results+0x3AE)
 c.flags=u32(r+0xAC1E4)
 assert(c.mode==1 and c.sequence==0 and c.resultPhase==0,'Mission is already clearing or not playing')
 assert(c.flags&amp;0x10000000==0,'Mission already frozen')
 -- GCL_ExecProc receives a script procedure ID here, not a RAM pointer.
 assert(byte(r+c.vr+0x108)==1,'Normal clear script unavailable')
 c.procedure=u32(r+c.vr+0x38)
 c.script,c.scriptBytes=procedure(r,c.procedure)
 return c
end
function M.apply()
 local c=M.inspect();local fresh=M.inspect()
 assert(fresh.ram==c.ram and fresh.stage==c.stage and fresh.work==c.work and fresh.vr==c.vr and fresh.results==c.results and fresh.flags==c.flags and fresh.procedure==c.procedure and fresh.script==c.script and fresh.scriptBytes==c.scriptBytes,'Mission changed; retry')
 -- Exactly the three state changes performed by the native clear handler D87B8.
 -- Set the sequence last: subsequent game updates perform clear presentation,
 -- script callbacks, completion bookkeeping and results through normal code.
 assert(writeInteger(c.ram+0xAC1E4,c.flags|0x10000000),'Could not freeze clear transition')
 assert(writeInteger(c.ram+0xE5F70,2),'Could not set normal clear mode')
 assert(writeBytes(c.ram+c.vr+0x10B,1),'Could not start normal clear sequence')
 M.last={pid=M.pid,stage=c.stage,ram=c.ram,vr=c.vr,results=c.results,flagsBefore=c.flags,procedure=c.procedure,script=c.script}
 VRMMissionClear=M
 return string.format('Normal clear requested in %s; VR actor=%08X results=%08X. Current timer and game result calculation retained.',c.stage,0x80000000+c.vr,0x80000000+c.results)
end
return M
]====]):sub(2),
 [ [====[VR-Missions/vrm-no-alert.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Data-only guard/camera suppression. Profiles are resolved from live MIPS code.
if VRMNoAlert then
 assert(VRMNoAlert.version==2 and VRMNoAlert.pid==getOpenedProcessID(),'Stop the previous no-alert controller before upgrading')
 return VRMNoAlert
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=VRMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'vrm-reader.lua')end
local D=dofile(dir..'vrm-discovery.lua')
local A={pid=R.pid,reader=R,discovery=D,version=2,enabled=false,wanted=false,status='OFF',rebinds=0,cache={}}
local MASK=0x17
local cameraNames={['camera.c']=true,['camera2.c']=true,['guncame.c']=true}
local function u16(a)return assert(readSmallInteger(a),'Short read unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Word read unavailable')&amp;0xFFFFFFFF end
local function byte(a)return assert(readBytes(a,1),'Byte read unavailable')end
local function put16(a,v)assert(writeSmallInteger(a,v&amp;0xFFFF),'Short write failed')end
local function put32(a,v)assert(writeInteger(a,v&amp;0xFFFFFFFF),'Word write failed')end
local function put8(a,v)assert(writeBytes(a,v&amp;255),'Byte write failed')end
local function stamp(ram,p,n)
 local b=assert(readBytes(ram+p,n or 16,true),'Code fingerprint unavailable')
 return string.char(table.unpack(b))
end
local function blocksValid(r,p)
 for _,b in ipairs(p.blocks or {})do if stamp(r,b.offset,#b.bytes)~=b.bytes then return false end end
 return true
end
local function family(a)return a.name..':'..a.act..':'..a.die end
local function actorSame(a,b)return a and b and a.offset==b.offset and a.act==b.act and a.die==b.die and a.name==b.name end
local function now()return getTickCount and getTickCount()or math.floor(os.clock()*1000)end
function A.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xac1e8)==0 and u32(ram+0xac848)~=0,'Area loading')
 local stage=assert(readString(ram+0xb5b98,16),'Stage unavailable')
 assert(stage:match('^[%w_]+$')and #stage&lt;=12,'Stage not ready')
 local actors=D.actors(ram);local present={};local families={};local samples={}
 for _,a in ipairs(actors)do
  present[a.offset]=a
  if a.name=='watcher.c'or cameraNames[a.name]or a.name=='command.c'then
   local key=family(a)
   if not families[key]then families[key]=true;samples[#samples+1]=key..stamp(ram,a.act&amp;0x1FFFFF,32)end
  end
 end
 table.sort(samples)
 local epoch=tostring(ram)..':'..stage
 local key=epoch..':'..table.concat(samples,'|')
 local profile=A.cache[key]
 if profile then
  if profile.guard and not blocksValid(ram,profile.guard)then profile=nil end
  if profile and profile.guard and stamp(ram,profile.guard.proofPC,32)~=profile.guard.proof then profile=nil end
  if profile then for _,p in pairs(profile.cameras)do if stamp(ram,p.loadPC,16)~=p.proof then profile=nil;break end end end
 end
 if not profile or (profile.unsupported&gt;0 and now()-(profile.time or 0)&gt;1000)then
  local code=D.overlay(ram)
  profile={cameras={},unsupported=0,time=now()}
  local p,why=D.guardProfile(ram,actors,code);profile.guard=p;profile.guardReason=why
  local checked={}
  for _,a in ipairs(actors)do
   if a.name=='watcher.c'and not p then profile.unsupported=profile.unsupported+1 end
   if cameraNames[a.name]and not checked[family(a)]then
    checked[family(a)]=true
    local cp,err=D.cameraProfile(a,code)
    if cp then cp.proof=stamp(ram,cp.loadPC,16);profile.cameras[family(a)]=cp
    else profile.unsupported=profile.unsupported+1;profile.cameraReason=err end
   end
  end
  if p then p.proofPC=p.visionPC-12;p.proof=stamp(ram,p.proofPC,32)end
  A.cache[key]=profile
 end
 local c={ram=ram,stage=stage,epoch=epoch,key=key,h=h,actors=present,profile=profile,guards=D.guardActors(ram,actors,profile.guard),cameras={}}
 for _,a in ipairs(actors)do
  local cp=profile.cameras[family(a)]
  if cp then a.cameraProfile=cp;c.cameras[a.offset]=a end
 end
 return c
end
local function fresh(c)
 -- Stage/DRAM changes unload the previous area. Never restore through its old
 -- addresses into a replacement overlay or replacement actor allocation.
 if not A.snapshot or A.snapshot.epoch~=c.epoch then
  A.snapshot={epoch=c.epoch,ram=c.ram,stage=c.stage,guards={},cameras={}}
  A.rebinds=A.rebinds+1
 end
 local s=A.snapshot;local p=c.profile.guard
 if p then
  if not s.guard or s.guard.profile.command~=p.command or s.guard.profile.proof~=p.proof then
   s.guard={profile=p,ranges={}}
  end
  for i=0,2 do
   local v=u16(c.ram+p.ranges+i*2)
   if v~=0x8000 then assert(v&lt;32768,'Existing negative guard range');s.guard.ranges[i+1]=v end
   assert(s.guard.ranges[i+1]~=nil,'Guard ranges already modified without ownership')
  end
 end
 return s
end
local function apply(c)
 local s=fresh(c);local ng,nc=0,0
 if c.profile.guard then
  local p=c.profile.guard
  for i=0,2 do if u16(c.ram+p.ranges+i*2)~=0x8000 then put16(c.ram+p.ranges+i*2,0x8000)end end
  if u32(c.ram+p.eye)~=0xFFFF8000 then put32(c.ram+p.eye,0xFFFF8000)end
  for o,g in pairs(c.guards)do
   ng=ng+1;local flags=byte(c.ram+o+0xBA3);local saved=s.guards[o]
   if not saved or not actorSame(saved.actor,g)or saved.actor.slot~=g.slot then saved={actor=g,mask=flags&amp;MASK};s.guards[o]=saved end
   saved.mask=saved.mask|(flags&amp;MASK)
   if flags&amp;MASK~=0 then put8(c.ram+o+0xBA3,flags&amp;(~MASK&amp;255))end
   for _,field in ipairs({0xB92,0xB94})do if u16(c.ram+o+field)~=0 then put16(c.ram+o+field,0)end end
   if u32(c.ram+o+0xB98)~=0 then put32(c.ram+o+0xB98,0)end
   for _,field in ipairs({0xBA1,0xBA2})do if byte(c.ram+o+field)~=0 then put8(c.ram+o+field,0)end end
  end
 end
 for o,camera in pairs(c.cameras)do
  nc=nc+1;local cp=camera.cameraProfile
  local v=cp.size==4 and u32(c.ram+o+cp.range)or u16(c.ram+o+cp.range);local old=s.cameras[o]
  if not old or not actorSame(old.actor,camera)or old.field~=cp.range or old.size~=cp.size or old.proof~=cp.proof then
   old={actor=camera,field=cp.range,size=cp.size,range=v,proof=cp.proof,pc=cp.loadPC};s.cameras[o]=old
  elseif v~=0 then old.range=v end -- reinitialized/replaced camera parameters
  if v~=0 then if cp.size==4 then put32(c.ram+o+cp.range,0)else put16(c.ram+o+cp.range,0)end end
 end
 A.guardCount=ng;A.cameraCount=nc;A.stage=c.stage;A.profile=c.profile
 A.status=string.format('ON | %s | %d guards, %d cameras | area binds %d',c.stage,ng,nc,A.rebinds)
 if c.profile.unsupported&gt;0 then A.status=A.status..' | PARTIAL: unrecognized sensing layout'end
end
local function restore()
 if not A.snapshot then return end
 assert(getOpenedProcessID()==A.pid,'Original process required for cleanup')
 local c=A.context();local s=A.snapshot
 if c.epoch~=s.epoch then A.snapshot=nil;return end
 local p=s.guard and s.guard.profile
 if p and blocksValid(c.ram,p)and stamp(c.ram,p.proofPC,32)==p.proof then
  for i,v in ipairs(s.guard.ranges)do put16(c.ram+p.ranges+(i-1)*2,v)end
  local mode=u32(c.ram+p.command+0x18)
  if mode&lt;=2 then local r=s.guard.ranges[mode+1];put32(c.ram+p.eye,r);put32(c.ram+p.shoot,r+500)end
 end
 for o,old in pairs(s.guards)do
  local g=c.actors[o]
  if actorSame(g,old.actor)and byte(c.ram+o+0xB78)==old.actor.slot then
   put8(c.ram+o+0xBA3,(byte(c.ram+o+0xBA3)&amp;(~MASK&amp;255))|old.mask)
  end
 end
 for o,old in pairs(s.cameras)do
  if actorSame(c.actors[o],old.actor)and stamp(c.ram,old.pc,16)==old.proof then
   if old.size==4 then put32(c.ram+o+old.field,old.range)else put16(c.ram+o+old.field,old.range)end
  end
 end
 A.snapshot=nil
end
function A.disable()
 A.wanted=false;A.enabled=false
 local ok,err=pcall(restore)
 if not ok then A.status='CLEANUP WAITING: '..tostring(err);return false,A.status end
 A.status='OFF';return true
end
function A.enable()
 assert(not A.stopped,'Reload the stopped no-alert controller')
 if A.wanted then return true end
 assert(not A.snapshot,'Finish pending cleanup before enabling')
 local c=A.context()
 A.wanted=true;A.enabled=true
 local ok,err=pcall(apply,c)
 if not ok then A.disable();error(err)end
 return true
end
function A.tick()
 if A.stopped then return end
 if not A.wanted then if A.snapshot then A.disable()end;return end
 if getOpenedProcessID()~=A.pid then A.enabled=false;A.status='WAITING: original process required';return end
 local ok,err=pcall(function()apply(A.context())end)
 if ok then A.enabled=true else A.enabled=false;A.status='WAITING FOR AREA: '..tostring(err)end
end
function A.stop()
 local ok,err=A.disable();if not ok then return false,err end
 A.stopped=true;A.timer.Enabled=false;A.timer.destroy();A.timer=nil
 if VRMNoAlert==A then VRMNoAlert=nil end
 return true
end
A.timer=createTimer(nil,false);A.timer.Interval=50;A.timer.OnTimer=A.tick;A.timer.Enabled=true
VRMNoAlert=A
return A
]====]):sub(2),
 [ [====[VR-Missions/vrm-ownership.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
local B={}
local function u32(a)return assert(readInteger(a),'Memory unavailable')&amp;0xFFFFFFFF end
local function psx(p,n)assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'PSX pointer invalid');return p&amp;0x1FFFFF end
local function s32(a)local n=u32(a);return n&gt;=0x80000000 and n-0x100000000 or n end
local function binary(r,o,n)
 assert(o&gt;=0 and n&gt;=0 and o+n&lt;=0x200000,'Capture outside RAM')
 local out={}
 for j=0,n-1,4096 do local k=math.min(4096,n-j);local t=assert(readBytes(r+o+j,k,true));assert(#t==k);out[#out+1]=string.char(table.unpack(t))end
 return table.concat(out)
end
local function signed(n)return n&gt;=32768 and n-65536 or n end
local function op(w)return w&gt;&gt;26 end
local function rs(w)return (w&gt;&gt;21)&amp;31 end
local function rt(w)return (w&gt;&gt;16)&amp;31 end
local function rd(w)return (w&gt;&gt;11)&amp;31 end
local function isBranch(w)return op(w)==1 or (op(w)&gt;=4 and op(w)&lt;=7)or op(w)==2 or op(w)==3 or (op(w)==0 and ((w&amp;63)==8 or (w&amp;63)==9))end
local function copy(t)local r={};for k,v in pairs(t)do r[k]=v end;return r end
local function destination(w)
 if op(w)==0 then return rd(w)end
 if (op(w)&gt;=8 and op(w)&lt;=15)or (op(w)&gt;=32 and op(w)&lt;=39)then return rt(w)end
end
-- Conservative backwards slice: only a direct work-field load, a move and/or
-- a left shift are accepted. Branches, calls and complex arithmetic reject it.
local function expression(words,aliases,at,reg,depth)
 if (depth or 0)&gt;5 then return nil end
 if reg==0 then return {kind='constant',value=0}end
 for i=at,math.max(1,at-24),-1 do
  local w=words[i];if isBranch(w)then return nil end
  if destination(w)==reg then
   if op(w)==35 then
    local base=aliases[i][rs(w)]
    if base~=nil and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     local offset=base+signed(w&amp;0xFFFF)
     if offset&gt;=0x20 and offset&lt;=0x4000 and offset%4==0 then return {kind='field',offset=offset,scale=1}end
    end
   elseif op(w)==9 and rs(w)==0 then return {kind='constant',value=signed(w&amp;0xFFFF)}
   elseif op(w)==13 and rs(w)==0 then return {kind='constant',value=w&amp;0xFFFF}
   elseif op(w)==0 then
    local f=w&amp;63
    if (f==33 or f==37)and (rs(w)==0 or rt(w)==0)then
     return expression(words,aliases,i-1,rs(w)==0 and rt(w)or rs(w),(depth or 0)+1)
    elseif f==0 and rs(w)==0 then
     local e=expression(words,aliases,i-1,rt(w),(depth or 0)+1);local shift=(w&gt;&gt;6)&amp;31
     if e and shift&lt;=4 then if e.kind=='field'then e.scale=e.scale*(1&lt;&lt;shift)else e.value=e.value*(1&lt;&lt;shift)end;return e end
    end
   end
   return nil
  end
 end
end
function B.ownership(r,actor)
 assert(binary(r,0x305F0,48)==string.char(0x7C,7,0x84,0x8F,0,0,0,0,0x40,0,0x82,0x28,3,0,0x40,0x14,0xC0,0x18,4,0,8,0,0xE0,3,0x21,0x10,0,0,0x21,0x18,0x64,0,0xC0,0x18,3,0,0x0B,0x80,2,0x3C,0xF0,0x72,0x42,0x24,0x21,0x18,0x62,0),'VR TARGET pool allocator differs')
 assert(binary(r,0x30690,16)==string.char(0x11,0,0x80,0x10,0x0B,0x80,3,0x3C,0x7C,7,0x85,0x8F,0xA8,0x72,0x63,0x24),'VR TARGET release differs')
 local e={targets={},fields={},proofs={},functions=0,blocks={}}
 local overlay=binary(r,0xC0000,0xA0000)
 local queue={{fn=actor.die,base=0},{fn=actor.act,base=0}};local seen={}
 local function mark(field,kind,pc,w)
  if field&lt;0x20 or field&gt;0x4000 then return end
  local v=e.fields[field]or {};e.fields[field]=v;v[kind]={pc=pc,word=w}
 end
 while #queue&gt;0 and e.functions&lt;128 do
  local item=table.remove(queue,1);local fn,base=item.fn,item.base;local key=tostring(fn)..':'..tostring(base)
  if item.aliases then for reg=1,31 do if item.aliases[reg]~=nil then key=key..':'..reg..'='..item.aliases[reg]end end end
  if not seen[key]and fn&gt;=0x800C0000 and fn&lt;0x80160000 and fn%4==0 then
   seen[key]=true;e.functions=e.functions+1
   local offset=(fn&amp;0x1FFFFF)-0xC0000
   local code=overlay:sub(offset+1,offset+0x1000);local words,aliases={},{};local alias=item.aliases or {[4]=base};local loaded={};local stop=false
   for i=1,#code//4 do
    local w=string.unpack('&lt;I4',code,(i-1)*4+1);local pc=fn+(i-1)*4;words[i]=w;aliases[i]=copy(alias)
    local o=op(w);local field=alias[rs(w)]and alias[rs(w)]+signed(w&amp;0xFFFF)
    if field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23))then
     if o==35 then mark(field,'read',pc,w);loaded[rt(w)]={field=field}
     elseif o==43 then mark(field,'write',pc,w);if loaded[rt(w)]and loaded[rt(w)].field==field and loaded[rt(w)].decrement then mark(field,'decrement',pc,w)end end
    end
    if o==35 and not(field and (rs(w)==4 or (rs(w)&gt;=16 and rs(w)&lt;=23)))then loaded[rt(w)]=nil end
    local dest=destination(w);local value
    if o==0 and ((w&amp;63)==33 or (w&amp;63)==37)then
     if rt(w)==0 then value=alias[rs(w)]elseif rs(w)==0 then value=alias[rt(w)]end
    elseif o==9 and alias[rs(w)]~=nil then value=alias[rs(w)]+signed(w&amp;0xFFFF)end
    if o==9 and rt(w)==rs(w)and signed(w&amp;0xFFFF)==-1 and loaded[rt(w)]then loaded[rt(w)].decrement=true
    elseif dest and dest~=0 and o~=35 then loaded[dest]=nil end
    if dest and dest~=0 then alias[dest]=value end
    local prior=words[i-1]
    if prior and (op(prior)==3 or op(prior)==2)then
     local callee=((prior&amp;0x3FFFFFF)&lt;&lt;2)|0x80000000
     if callee==0x80030690 then
      local exp
      if destination(w)==4 then
       exp=expression({w},{aliases[i]},1,4)
       if not exp and op(w)==0 and ((w&amp;63)==33 or (w&amp;63)==37)and (rs(w)==0 or rt(w)==0)then exp=expression(words,aliases,i-2,rs(w)==0 and rt(w)or rs(w))end
      else exp=expression(words,aliases,i-2,4)end
      if exp and exp.kind=='field'and exp.scale==1 then e.targets[exp.offset]={field=exp.offset,pc=pc-4,word=prior}end
     elseif callee&gt;=0x800C0000 and callee&lt;0x80160000 then
      if op(prior)==2 then
       -- Follow a real unconditional control-flow edge, preserving its work
       -- aliases. Do not fall through into the next unrelated function.
       queue[#queue+1]={fn=callee,aliases=copy(alias)}
      elseif alias[4]and alias[4]&gt;=0 and alias[4]&lt;0x4000 then queue[#queue+1]={fn=callee,base=alias[4]}end
     end
     for j=2,15 do alias[j]=nil;loaded[j]=nil end;alias[24]=nil;alias[25]=nil
    end
    if stop then break end
    if o==2 or (o==0 and (w&amp;63)==8 and rs(w)==31)then stop=true end
   end
   e.blocks[#e.blocks+1]={address=r+(fn&amp;0x1FFFFF),bytes=code:sub(1,#words*4)}
  end
 end
 return e
end

return B
]====]):sub(2),
 [ [====[VR-Missions/vrm-reader.lua]====] ]=([====[!-- US Master Collection VR Missions (SLUS_009.57), host build 20872173.
-- All target access in this module is read-only.
assert(process=='METAL GEAR SOLID.exe','Attach to METAL GEAR SOLID.exe')
assert(getModuleSize(process)==30007296,'Unsupported executable image size')
local base,pid=getAddress(process),getOpenedProcessID()
local R={pid=pid,module=base,vtable=base+0xAB8CF0,version=1,variant='VR Missions US'}
local function bytes(a,n)
 local b=assert(readBytes(a,n,true),'Memory unavailable')
 assert(#b==n,'Incomplete memory read');return b
end
local function fp(a,hex)
 local expected=hex:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)
 local b=bytes(a,#expected)
 assert(string.char(table.unpack(b))==expected,'VR Missions code/layout differs at '..string.format('%X',a))
end
fp(base+0x10B43D,'488D05ACD89A00')
fp(base+0x10B447,'41B900400800')
local function validate(ram)
 assert(ram and ram&gt;0x10000,'Emulated RAM missing')
 assert(readString(ram+0x10000,11)=='SLUS_009.57','Only US VR Missions SLUS_009.57 is supported')
 -- Actual health load, three-way health synchronization, and alert globals.
 fp(ram+0x51584,'0B80023CBE5B4284')
 fp(ram+0x52974,'A85B47249808258E1600E2842600A384')
 fp(ram+0x52A7C,'212020029808828C0001053C260046A40B80023C1E0A86A4BE5B46A4')
 fp(ram+0x31B24,'0B80043C10C8848C')
 fp(ram+0x31C08,'0B80033C28C8638C')
end
function R.checkFeature(kind)
 local r=R.ram;validate(r)
 if kind=='health'then
  fp(r+0x52454,'4245010C8000043C9808038E200A11A2000062940000000069FF4230000062A4')
  fp(r+0x51508,'0B80023C60C8428C00000000251044000B80013C60C822AC0800E00300000000')
  fp(r+0x524AC,'9808038E0000000000006294000000009E004234000062A4')
 elseif kind=='ammo'then
  fp(r+0x66784,'0B80023CCA5B43940C0004240B80013CFCC730A40B80013C3CC824A4FFFF6324CA5B43A4')
 elseif kind=='inventory'then
  fp(r+0x5446C,'0B80023CA85B52241C00428604008012180902AE')
  fp(r+0x547E4,'0B80023CA85B52241E0042860400A012A40922AE')
 else error('Unsupported VR feature')end
end
local pattern={}
for i=0,7 do pattern[#pattern+1]=string.format('%02X',(R.vtable&gt;&gt;(i*8))&amp;255)end
local found=AOBScan(table.concat(pattern,' '),'+W-C',fsmAligned,'8')
local candidates={}
if found then
 for i=0,found.Count-1 do
  local owner=tonumber(found[i],16);local ram=readQword(owner+0x28)
  if pcall(validate,ram)then candidates[#candidates+1]={owner=owner,ram=ram}end
 end
 found.destroy()
end
assert(#candidates==1,'Expected one validated VR Missions RAM owner; found '..#candidates)
R.owner,R.ram=candidates[1].owner,candidates[1].ram
local function u16(b,o)return b[o+1]|(b[o+2]&lt;&lt;8)end
local function s16(b,o)local n=u16(b,o);return n&gt;=32768 and n-65536 or n end
local function u32(b,o)return u16(b,o)|(u16(b,o+2)&lt;&lt;16)end
R.weapons={'SOCOM','FAMAS','Grenade','Nikita','Stinger','Claymore','C4','Stun grenade','Chaff grenade','PSG1'}
R.modes={[0]='NORMAL',[1]='JAMMING',[2]='EVASION',[3]='ALERT'}
function R.read()
 assert(getOpenedProcessID()==pid and process=='METAL GEAR SOLID.exe','Process changed; reload VR controls')
 assert(readQword(R.owner)==R.vtable,'Emulator owner changed')
 local ram=readQword(R.owner+0x28)
 -- Game selection can replace the guest inside the SAME allocation.
 validate(ram);R.ram=ram
 local stage=readString(ram+0xB5B98,16)
 assert(stage and stage:match('^vr_[%w_]+$')and #stage&lt;=12,'Enter a VR mission')
 local q,g=bytes(ram+0xB5BA8,192),bytes(ram+0xAC7F8,0x50)
 local h={pid=pid,ram=ram,stage=stage,health=s16(q,0x16),maximum=s16(q,0x18),
  weapon=s16(q,0x1C),item=s16(q,0x1E),magazine=s16(g,4),magazineMax=s16(g,0x44),
  alertMode=u32(g,0x18),alertLevel=u32(g,0x30),ration=s16(q,0x64),rationMax=s16(q,0x7A),ammo={},ammoMax={}}
 assert(h.maximum&gt;=1 and h.maximum&lt;=2000 and h.health&gt;=0 and h.health&lt;=h.maximum,'Health layout invalid')
 assert(h.weapon&gt;=-1 and h.weapon&lt;=9 and h.item&gt;=-1 and h.item&lt;=23,'Equipment layout invalid')
 assert(R.modes[h.alertMode]and h.alertLevel&lt;=65535,'Alert layout invalid')
 for i=1,10 do h.ammo[i]=s16(q,0x22+(i-1)*2);h.ammoMax[i]=s16(q,0x36+(i-1)*2)end
 h.weaponName=h.weapon==-1 and 'None'or R.weapons[h.weapon+1]
 h.ammoSelected=h.weapon&gt;=0 and h.ammo[h.weapon+1]or nil
 h.ammoSelectedMax=h.weapon&gt;=0 and h.ammoMax[h.weapon+1]or nil
 h.alertName=R.modes[h.alertMode]
 return h
end
VRMReader=R
return R
]====]):sub(2),
 [ [====[VR-Missions/vrm-timer.lua]====] ]=([====[!-- Discover and hold the normal vr.c mission timer; no fixed stage/actor address.
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
if VRMTimer and VRMTimer.pid==getOpenedProcessID()then return VRMTimer end
if VRMTimer then VRMTimer.disable()end
local G=dofile(dir..'vrm-inventory.lua')
local F={pid=G.pid,wanted=false,version=1,status='Mission timer freeze OFF',binds=0,writes=0}
local function u16(a)return assert(readSmallInteger(a),'Timer short unavailable')&amp;0xFFFF end
local function u32(a)return assert(readInteger(a),'Timer word unavailable')&amp;0xFFFFFFFF end
local function blob(a,n)
 local b=assert(readBytes(a,n,true),'Timer code unavailable');assert(#b==n,'Short timer read')
 local out={};for _,v in ipairs(b)do out[#out+1]=string.char(v)end;return table.concat(out)
end
local function hex(s)return(s:gsub('%x%x',function(v)return string.char(tonumber(v,16))end))end
local header=hex('d0ffbd272000b0af21808000c800042421288000213080002800bfaf43ef000c2400b1af1801028e0000000001004230e8004014')
local counter=hex('1801028e000000004210020001004230190040140e80113c0e80023c7078438c010002241400621400000000340002963600038601004224340002a600140200031402000c00621421200000')
local draw=hex('8888043c360003863400028689888434232862001800a400c31f050010c0000021100503')
local die=hex('e8ffbd27211080001000bfaf4800448c00000000040080100000000034004584')
local function profile(r,act,death)
 assert(act&gt;=0x800C0000 and act+0x7A0&lt;0x80160000 and act%4==0 and death==act+0x780,'Unsupported timer actor callbacks')
 local o=act&amp;0x1FFFFF
 assert(blob(r+o,#header)==header and blob(r+o+0xE4,#draw)==draw and blob(r+(death&amp;0x1FFFFF),#die)==die,'Unsupported native timer layout')
 local b=blob(r+o+0x35C,#counter)
 for i=0,#counter//4-1 do
  local actual,expected=string.unpack('&lt;I4',b,i*4+1),string.unpack('&lt;I4',counter,i*4+1)
  local mask=(i==5 or i==6 or i==7)and 0xFFFF0000 or 0xFFFFFFFF
  assert(actual&amp;mask==expected&amp;mask,'Timer increment/expiry code differs')
 end
 local high=string.unpack('&lt;I4',b,6*4+1)&amp;0xFFFF
 local low=string.unpack('&lt;I4',b,7*4+1)&amp;0xFFFF;if low&gt;=32768 then low=low-65536 end
 local mode=(high&lt;&lt;16)+low
 assert(mode&gt;=0x800C0000 and mode+4&lt;0x80160000,'Timer play-mode binding invalid')
 return {mode=mode&amp;0x1FFFFF,act=act,die=death,proof=b}
end
function F.inspect()
 assert(getOpenedProcessID()==F.pid,'Attached process changed')
 local c=G.context(false);local r=c.ram
 assert(c.stage:match('^vr_[%w_]+$'),'Enter a VR mission')
 local start=0xADA28+5*0x44;local finish=start+0x20
 local previous=start;local p=u32(r+start+4);local seen={};local found
 for _=1,256 do
  assert(p&gt;=0x80010000 and p+0x120&lt;=0x80200000,'Timer actor pointer invalid')
  local o=p&amp;0x1FFFFF
  assert(u32(r+o)==0x80000000+previous,'Timer actor list changed')
  if o==finish then break end
  assert(not seen[o],'Timer actor list cycle');seen[o]=true
  local n=u32(r+o+20)
  if n&gt;=0x80010000 and n&lt;0x80200000 and readString(r+(n&amp;0x1FFFFF),48)=='vr.c' then
   assert(not found,'Multiple mission timer actors');found=o
  end
  previous=o;p=u32(r+o+4)
 end
 assert((p&amp;0x1FFFFF)==finish and found,'Normal mission timer actor unavailable')
 c.actor=found;c.profile=profile(r,u32(r+found+8),u32(r+found+12))
 c.elapsed=u16(r+found+0x34);c.limit=u16(r+found+0x36)
 c.timerFlags=u32(r+found+0x118);c.mode=u32(r+c.profile.mode)
 c.display=assert(readBytes(r+found+0x44,1))
 c.menu=u16(r+0xBE4F0+0x2A);c.remaining=c.limit-c.elapsed
 c.ready=c.ready and c.mode==1 and c.timerFlags&amp;2==0 and c.menu==0 and u32(r+0xAC1E4)&amp;0x10000000==0 and assert(readBytes(r+found+0x10B,1))==0
 c.supported=c.display==1 and c.limit&gt;0 and c.limit&lt;32768 and c.elapsed&lt;32768
 return c
end
function F.tick()
 if not F.wanted or F.busy then return end
 if getOpenedProcessID()~=F.pid then F.disable();F.status='Stopped: process changed';return end
 F.busy=true
 local ok,err=pcall(function()
  local c=F.inspect()
  assert(c.supported,'Mission does not use the supported visible timer')
  if not c.ready then F.binding=nil;F.status='Waiting for active mission play';return end
  local key=c.ram..':'..c.stage..':'..c.actor..':'..c.profile.act..':'..c.limit
  local b=F.binding
  if not b or b.key~=key or c.elapsed&lt;b.held then
   assert(c.remaining&gt;=15,'Restart mission: timer is expired or too close to expiry')
   b={key=key,held=c.elapsed,ram=c.ram,actor=c.actor,act=c.profile.act,die=c.profile.die,limit=c.limit,stage=c.stage}
   F.binding=b;F.binds=F.binds+1
  end
  -- Only the actor-owned elapsed counter is held. The global clock, limit,
  -- AI, animation, scores and native instructions are never written here.
  if c.elapsed~=b.held then
   assert(u32(c.ram+c.actor+8)==b.act and u32(c.ram+c.actor+12)==b.die and u16(c.ram+c.actor+0x36)==b.limit and u32(c.ram+c.profile.mode)==1,'Timer owner/state changed')
   assert(writeSmallInteger(c.ram+c.actor+0x34,b.held),'Could not hold mission timer');F.writes=F.writes+1
  end
  F.state=c;F.status=string.format('Timer freeze ON | %s | %.2f seconds left | binds %d',c.stage,(c.limit-b.held)/30,F.binds)
 end)
 if not ok then F.binding=nil;F.state=nil;F.status='Waiting: '..tostring(err)end
 F.busy=false
end
function F.enable()
 assert(F.pid==getOpenedProcessID(),'Attached process changed')
 F.wanted=true
 if not F.timer then F.timer=createTimer(nil,false);F.timer.Interval=10;F.timer.OnTimer=F.tick end
 F.timer.Enabled=true;F.tick();return true
end
function F.disable()
 F.wanted=false;if F.timer then F.timer.Enabled=false;F.timer.destroy();F.timer=nil end
 F.binding=nil;F.state=nil;F.status='Mission timer freeze OFF; normal ticking resumes'
 return true
end
VRMTimer=F;return F
]====]):sub(2),
 [ [====[VR-Missions/vrm-toggles.lua]====] ]=([====[!-- Generated by analysis/vr-missions/build-port.py; see it for mapping evidence.
-- Generated by analysis/build-vrm-special-health.py.
-- Optional data-only cheats for the validated US VR Missions layout.
-- No game code patches, injected calls or debugger attachment.
if VRMToggles then
 assert(VRMToggles.pid==getOpenedProcessID(),'Stop the old controller before changing processes')
 return VRMToggles
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=VRMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'vrm-reader.lua')end
local T={pid=R.pid,reader=R,version=3,health={enabled=false,requested=false,rebinds=0,status='OFF'},ammo={enabled=false,status='OFF'},stopped=false}
local INV=0x00800000
local MASK=0x0096
local function u16(address)return assert(readSmallInteger(address),'Cannot read 16-bit value')&amp;0xFFFF end
local function u32(address)return assert(readInteger(address),'Cannot read 32-bit value')&amp;0xFFFFFFFF end
local function put16(address,value,mask)
 assert(writeSmallInteger(address,value&amp;0xFFFF),'16-bit write failed')
 if mask~=false then
  mask=mask or 0xFFFF
  assert(u16(address)&amp;mask==(value&amp;mask),'16-bit verification failed')
 end
end
local function put32(address,value,mask)
 assert(writeInteger(address,value&amp;0xFFFFFFFF),'32-bit write failed')
 mask=mask or 0xFFFFFFFF
 assert(u32(address)&amp;mask==(value&amp;mask),'32-bit verification failed')
end
local function put8(address,value)
 assert(writeBytes(address,value&amp;255),'Byte write failed')
 assert(readBytes(address,1)==value,'Byte verification failed')
end
local function fingerprint(address,expected)
 local actual=readBytes(address,#expected,true)
 assert(actual and #actual==#expected,'Protection code unavailable')
 for i,v in ipairs(expected)do assert(actual[i]==v,'Unsupported protection code fingerprint')end
end
local function psx(pointer,size)
 assert(pointer and pointer&gt;=0x80000000 and pointer&lt;0x80200000,'Invalid PlayStation pointer')
 local offset=pointer&amp;0x1FFFFF
 assert(offset+(size or 1)&lt;=0x200000,'PlayStation object exceeds RAM')
 return offset
end
function T.context()
 local h=R.read();local ram=h.ram
 assert(u32(ram+0xac1e8)==0 and u32(ram+0xac848)~=0,'Area loading')
 local control=u32(ram+0xac804)
 local work=psx(control,0x100)-0x20
 assert(work&gt;=0 and work+0xA24&lt;0x200000,'Invalid Snake actor bounds')
 assert(u32(ram+work+8)==0x8005d5ac and u32(ram+work+0xC)==0x8005dc00,'Snake actor is not live')
 assert(u32(ram+0xac830)==0x80000000+work+0x9C,'Snake body owner mismatch')
 local target=psx(u32(ram+work+0x898),0x48)
 assert(u16(ram+target+2)==1,'Collision target is not on the player side')
 return {h=h,ram=ram,work=work,target=target,status=ram+0xac860}
end
local function sameOwner(c,s)
 return c.ram==s.ram and c.work==s.work and c.target==s.target
end
local function checkCode(ram)
 R.checkFeature('health');R.checkFeature('ammo')
end
local function applyHealth(c,s)
 assert(sameOwner(c,s),'Snake actor/RAM changed; stop and re-enable protection in gameplay')
 -- Match the game's invulnerability state. Zero frames means no expiration.
 local status=u32(c.status)
 if status&amp;INV==0 then put32(c.status,status|INV,INV)end
 if readBytes(c.ram+c.work+0xA20,1)~=0 then put8(c.ram+c.work+0xA20,0)end
 local class=u16(c.ram+c.target)
 if class&amp;MASK~=0 then put16(c.ram+c.target,class&amp;(~MASK&amp;0xFFFF),MASK)end
end
local function restoreHealth(s)
 if not s.owner then return true end
 assert(getOpenedProcessID()==T.pid,'Cannot restore while attached to another process')
 local c=T.context()
 if not sameOwner(c,s.owner)then
  -- The original actor has been replaced. Its old fields are no longer ours
  -- to write; the new actor was not patched by this ownership record.
  s.owner=nil;return true
 end
 -- Restore only our collision-mask bits, preserving unrelated current flags.
 put16(c.ram+c.target,(u16(c.ram+c.target)&amp;(~MASK&amp;0xFFFF))|s.originalMask,MASK)
 put8(c.ram+c.work+0xA20,0)
 put32(c.status,u32(c.status)&amp;(~INV&amp;0xFFFFFFFF),INV)
 s.owner=nil
 return true
end
local function applyAmmo(c)
 local h=c.h
 for i=1,10 do
  local current,capacity=h.ammo[i],h.ammoMax[i]
  -- Leave unowned weapons and undefined capacities alone.
  if current&gt;=0 and capacity&gt;0 and capacity&lt;=32767 and current&lt;capacity then
   put16(c.ram+0xb5bca+(i-1)*2,capacity,false)
  end
 end
 -- These three firearms use the shared magazine fields. Never change capacity.
 if h.weapon==0 or h.weapon==1 or h.weapon==9 then
  local capacity=h.magazineMax
  if capacity&gt;0 and capacity&lt;=500 and h.magazine&gt;=0 and h.magazine&lt;capacity then
   local total=h.ammoMax[h.weapon+1]
   if total&gt;0 then put16(c.ram+0xac7fc,math.min(capacity,total),false)end
  end
 end
end
function T.disable(kind)
 local s=assert(T[kind],'Unknown option')
 s.enabled=false
 if kind=='health'then s.requested=false end
 if kind=='health'and s.owner then
  local ok,err=pcall(restoreHealth,s)
  if not ok then s.status='RESTORE PENDING: '..tostring(err);return false,s.status end
 end
 s.mode=nil;s.status='OFF'
 return true
end
local function specialRead()
 local h=R.read();h.stage=readString(h.ram+0xb5b98,16)
 assert(h.stage and h.stage:match('^[%w_]+$')and #h.stage&lt;=12,'Enter US VRM gameplay')
 return h
end
-- US VRM jeep actor: global vitality refill only; never normal Snake fields.
local function jeepContext()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=specialRead();local r=h.ram
 assert((h.stage=='s19b' or h.stage=='s19br') and h.health&gt;0 and u32(r+0xac1ec)==0,'Enter living jeep gameplay')
 assert(u32(r+0xac1e8)==0 and u32(r+0xac848)~=0,'Jeep area loading')
 assert(u32(r+0xae0a0)==0 and u32(r+0xac1e4)==0x20000000 and u32(r+0xac860)==0,'Finish jeep scene or pause')
 assert(u32(r+0xbfad0)==0x8003b864 and u32(r+0xbfad4)==0x8003b9a8 and u16(r+0xbfaf2)==0,'Close the menu')
 local work=psx(u32(r+0xac804),0x100)-0x20
 assert(work&gt;=0x10000 and work+0x100&lt;0x200000,'Jeep actor bounds differ')
 assert(u32(r+work+8)==0x800167fc and u32(r+work+12)==0x800e1180,'Jeep actor identity differs')
 assert(readString(r+0xe1180,10)=='jeep_sne.c','Jeep actor label differs')
 assert(u32(r+0xac830)==0x80000000+work+0x9c,'Jeep body ownership differs')
 for _,p in ipairs({{offset=0x167FC,bytes={232,255,189,39,16,0,191,175,33,40,128,0,55,89,0,12,2,0,4,36,16,0,191,143,24,0,189,39,8,0,224,3}},{offset=0xD79A4,bytes={16,9,67,142,11,128,2,60,38,117,66,148,0,0,0,0,38,0,98,164,11,128,8,60,38,117,8,37,0,0,2,133,60,9,67,142,16,9,69,142,35,16,67,0,38,0,164,132,11,128,3,60,40,117,99,132,33,32,130,0,42,16,100,0,3,0,64,16,0,20,4,0,33,32,96,0,0,20,4,0,3,20,2,0,38,0,164,164,60,9,66,174,69,0,64,28,0,0,2,165}},{offset=0xD7AA8,bytes={11,128,2,60,60,219,66,140,0,64,3,60,36,16,67,0,21,0,64,20,1,0,2,36,11,128,1,60,38,117,32,164,59,179,0,12,0,0,0,0,33,32,0,0,26,0,5,36,255,255,2,36,11,128,1,60,68,219,34,172,1,0,2,36,202,209,0,12,80,9,66,174,11,128,2,60,60,219,66,140,0,16,3,60,37,16,67,0,11,128,1,60,60,219,34,172,198,94,3,8,0,0,0,0,11,128,1,60,38,117,34,164}}})do fingerprint(r+p.offset,p.bytes)end
 checkCode(r)
 return {h=h,ram=r,work=work}
end
local function applyJeepHealth()
 local c=jeepContext();local fresh=jeepContext()
 assert(c.ram==fresh.ram and c.work==fresh.work and c.h.maximum==fresh.h.maximum,'Jeep owner changed')
 -- The jeep uses global vitality. It has no normal Snake target/mask layout.
 if fresh.h.health&lt;fresh.h.maximum then put16(fresh.ram+0xb5bbe,fresh.h.maximum)end
 local s=T.health
 if s.mode~='jeep' then s.rebinds=s.rebinds+1 end
 s.owner=nil;s.resumeOwned=nil;s.mode='jeep';s.requested=true;s.enabled=true
 s.status='ON - jeep health refill | normal invulnerability resumes after jeep'
 return true
end

-- rope.c owns a separate TARGET at work+804. Its Act copies target+26 to
-- GM_Vitality; refilling GM_Vitality alone cannot prevent its death branch.
local ropeProofs={{offset=0xCAC6C,bytes={176,255,189,39,68,0,177,175,33,136,128,0,72,0,178,175,156,0,50,38,11,128,2,60,60,219,66,140,8,0,3,60,76,0,191,175,64,0,176,175,37,16,67,0,11,128,1,60,60,219,34,172,11,128,6,60,136,225,198,36,35,0,34,138,32,0,34,154,39,0,35,138,36,0,35,154,3,0,194,168,0,0,194,184,7,0,195,168,4,0,195,184,135,218,0,12,33,32,64,2,4,8,34,142,0,0,0,0,38,0,66,132,0,0,0,0,5,0,64,28,32,0,48,38,117,0,34,146}},{offset=0xCAF60,bytes={4,8,34,142,0,0,0,0,38,0,66,148,11,128,3,60,38,117,99,36,0,0,98,164,0,20,2,0,2,0,65,4,0,0,0,0,0,0,96,164,213,42,3,12,33,32,32,2}},{offset=0xC70EC,bytes={224,255,189,39,16,0,176,175,33,128,128,0,28,0,191,175,24,0,178,175,20,0,177,175,112,15,3,142,0,0,0,0,0,33,98,48,153,0,64,20,0,128,98,48,4,8,17,142,0,0,0,0,6,0,50,150,54,0,64,16,4,0,66,50}},{offset=0xC7280,bytes={6,0,34,150,40,0,32,166,42,0,32,166,251,255,66,48,6,0,34,166,11,128,5,60,236,218,165,36,3,0,162,136,0,0,162,152,7,0,163,136,4,0,163,152,47,0,34,170,44,0,34,186,51,0,35,170,48,0,35,186,38,0,34,134,0,0,0,0,14,0,64,28,0,0,0,0,11,128,3,60,60,219,99,140,13,128,2,60,144,168,66,36,172,14,2,174,176,14,0,174,190,14,0,166,188,14,0,166,0,32,99,52,11,128,1,60,60,219,35,172,222,28,3,8,0,0,0,0}},{offset=0xC706C,bytes={32,0,2,36,124,15,130,172,112,15,130,140,4,8,131,140,0,128,66,52,112,15,130,172,0,0,98,148,0,0,0,0,235,255,66,48,8,0,224,3,0,0,98,164,112,15,130,140,4,8,131,140,124,15,133,172,0,128,66,52,112,15,130,172,0,0,98,148,0,0,0,0,235,255,66,48,8,0,224,3,0,0,98,164}}}
local ROPE_MASK=0x14 -- Native TARGET_POWER | TARGET_SEEK.
local function ropeContext()
 assert(getOpenedProcessID()==T.pid,'Attached process changed')
 local h=specialRead();local r=h.ram
 assert(h.stage=='s11d'and h.health&gt;0 and u32(r+0xac1ec)==0,'Enter living rappel gameplay')
 assert(u32(r+0xac1e8)==0 and u32(r+0xac848)~=0 and u32(r+0xae0a0)==0,'Rappel loading or paused')
 assert(u32(r+0xac1e4)==0x20488000 and u32(r+0xac860)==0,'Finish the rappel scene')
 assert(u32(r+0xbfad0)==0x8003b864 and u32(r+0xbfad4)==0x8003b9a8 and u16(r+0xbfaf2)==0,'Close the menu')
 local work=psx(u32(r+0xac804),0x10)-0x20
 assert(work&gt;=0x10000 and work+0x1098&lt;=0x200000,'Rappel actor bounds differ')
 assert(u32(r+work+8)==0x800cac6c and u32(r+work+12)==0x800cafac and u32(r+work+20)==0x800d4e0c,'Rappel actor identity differs')
 assert(readString(r+0xd4e0c,6)=='rope.c'and u32(r+0xac830)==0x80000000+work+0x9c,'Rappel body/label differs')
 for _,p in ipairs(ropeProofs)do fingerprint(r+p.offset,p.bytes)end
 checkCode(r)
 local target=psx(u32(r+work+0x804),0x48)
 local hp=u16(r+target+0x26)
 assert(u16(r+target+2)==1 and hp&gt;0 and hp&lt;=h.maximum,'Rappel target side/health invalid or depleted')
 local state=u32(r+work+0xeac)
 assert(state&gt;=0x800c6524 and state&lt;0x800cac6c and state~=0x800ca7c4 and state~=0x800ca890 and state~=0x800cab04,'Rappel death/unsupported state')
 return {h=h,ram=r,work=work,target=target}
end
local function ropeSame(c,s)return c.ram==s.ram and c.work==s.work and c.target==s.target end
local function applyRopeHealth()
 local c=ropeContext();local fresh=ropeContext()
 assert(ropeSame(c,fresh)and c.h.maximum==fresh.h.maximum,'Rappel owner changed')
 local s=T.health;local owner=s.ropeOwner
 if not owner or not ropeSame(fresh,owner)then
  owner={ram=fresh.ram,work=fresh.work,target=fresh.target,mask=u16(fresh.ram+fresh.target)&amp;ROPE_MASK}
  s.ropeOwner=owner;s.rebinds=s.rebinds+1
 end
 local a=fresh.ram+fresh.target
 if u16(a)&amp;ROPE_MASK~=0 then put16(a,u16(a)&amp;(~ROPE_MASK&amp;0xffff),ROPE_MASK)end
 -- Cancel already-delivered damage, then heal the authoritative private HP.
 if u16(a+6)&amp;4~=0 then put16(a+6,u16(a+6)&amp;0xfffb,4)end
 for _,o in ipairs({0x28,0x2a})do if u16(a+o)~=0 then put16(a+o,0)end end
 if u16(a+0x26)~=fresh.h.maximum then put16(a+0x26,fresh.h.maximum)end
 if fresh.h.health~=fresh.h.maximum then put16(fresh.ram+0xb5bbe,fresh.h.maximum)end
 s.owner=nil;s.resumeOwned=nil;s.mode='rappel';s.requested=true;s.enabled=true
 s.status='ON - rappel target immunity + private health protection'
 return true
end
local function restoreRopeHealth()
 local s=T.health;local owner=s.ropeOwner;if not owner then return true end
 assert(getOpenedProcessID()==T.pid,'Original process required for rappel restoration')
 local h=specialRead();local p=u32(h.ram+0xac804)
 if h.ram~=owner.ram or h.stage~='s11d'or p~=0x80000000+owner.work+0x20 or u32(h.ram+owner.work+8)~=0x800cac6c then
  s.ropeOwner=nil;return true -- Replaced actors do not own these fields.
 end
 local c=ropeContext();assert(ropeSame(c,owner),'Rappel target changed before restoration')
 local a=c.ram+c.target
 put16(a,(u16(a)&amp;(~ROPE_MASK&amp;0xffff))|owner.mask,ROPE_MASK)
 s.ropeOwner=nil;return true
end
local disableNormal=T.disable
function T.disable(kind)
 if kind=='health'then
  T.health.requested=false;T.health.enabled=false
  local ok,err=pcall(restoreRopeHealth)
  if not ok then T.health.status='RESTORE PENDING: '..tostring(err);return false,T.health.status end
 end
 return disableNormal(kind)
end
local function applySpecialHealth()
 local h=specialRead()
 if h.stage=='s11d'then return applyRopeHealth()end
 local ok=applyJeepHealth();T.health.ropeOwner=nil;return ok
end

function T.enable(kind)
 assert(not T.stopped,'Reload the stopped controller')
 local s=assert(T[kind],'Unknown option')
 if s.enabled then return true end
 assert(not s.owner,'Finish pending health restoration before re-enabling')
 local ok,c=pcall(T.context)
 if not ok then
  if kind=='health'then return applySpecialHealth()end
  error(c)
 end
 checkCode(c.ram)
 assert(c.h.health&gt;0 and u32(c.ram+0xac1ec)==0,'Enter normal living gameplay before enabling')
 if kind=='health'then
  local existing=u32(c.status)&amp;INV~=0
  local frames=assert(readBytes(c.ram+c.work+0xA20,1),'Cannot read invulnerability frames')
  assert(not existing or (frames&gt;0 and frames&lt;128)or s.resumeOwned,'An existing permanent invulnerability state is active; leave it unchanged')
  -- A normal hit's temporary immunity can be extended. OFF then performs its
  -- normal expiration mask, rather than preserving that temporary no-hit mask.
  s.originalMask=existing and MASK or (u16(c.ram+c.target)&amp;MASK)
  s.owner={ram=c.ram,work=c.work,target=c.target}
  local ok,err=pcall(function()
   applyHealth(c,s.owner)
   -- Synchronize the three health values once; no health-value freeze loop.
   put16(c.ram+c.target+0x26,c.h.maximum)
   put16(c.ram+c.work+0xA1E,c.h.maximum)
   put16(c.ram+0xb5bbe,c.h.maximum)
  end)
  if not ok then
   local restored,restoreError=pcall(restoreHealth,s)
   s.status=restored and ('OFF: '..tostring(err))or ('RESTORE PENDING: '..tostring(restoreError))
   error(s.status)
  end
  s.mode='normal';s.status='ON - native invulnerability + initial heal'
  s.requested=true;s.resumeOwned=nil
 elseif kind=='ammo'then
  applyAmmo(c);s.ram=c.ram;s.work=c.work
  s.status='ON - owned ammo/magazines replenish'
 else error('Unknown option')end
 s.enabled=true
 return true
end
function T.tick()
 if T.stopped then return end
 if not T.health.requested and not T.ammo.enabled and not T.health.owner and not T.health.ropeOwner then return end
 -- Retry our own pending restoration when gameplay becomes readable again.
 if not T.health.requested and (T.health.owner or T.health.ropeOwner)then T.disable('health')end
 if not T.health.requested and not T.ammo.enabled then return end
 local ok,c=pcall(T.context)
 if not ok then
  local ammoWasEnabled=T.ammo.enabled
  T.health.enabled=false;T.ammo.enabled=false
  if ammoWasEnabled then T.ammo.status='OFF: '..tostring(c)end
  if T.health.requested then T.health.status='WAITING FOR AREA: '..tostring(c)
  elseif T.health.owner then T.health.status='RESTORE PENDING: '..tostring(c)end
  if T.health.requested then
   local applied,err=pcall(applySpecialHealth)
   if not applied then T.health.status='WAITING FOR AREA: '..tostring(err)end
  end
  return
 end
 T.health.ropeOwner=nil -- Normal actor identity proves special actor replacement.
 if T.health.requested then
  local rebound=T.health.owner and not sameOwner(c,T.health.owner)
  if rebound then
   T.health.resumeOwned=T.health.owner.ram==c.ram
   T.health.owner=nil;T.health.enabled=false
  end
  local applied,err=pcall(function()
   if not T.health.owner then T.health.enabled=false;T.enable('health')
   else applyHealth(c,T.health.owner)end
  end)
  if not applied then
   T.health.enabled=false;T.health.status='WAITING FOR AREA: '..tostring(err)
  else
   if rebound then T.health.rebinds=T.health.rebinds+1 end
   T.health.enabled=true;T.health.status='ON - native invulnerability | area rebinds '..T.health.rebinds
  end
 end
 if T.ammo.enabled then
  if c.ram~=T.ammo.ram or c.work~=T.ammo.work then
   T.ammo.enabled=false;T.ammo.status='OFF: actor/RAM changed; re-enable in gameplay'
  else
   local applied,err=pcall(applyAmmo,c)
   if not applied then T.ammo.enabled=false;T.ammo.status='OFF: '..tostring(err)end
  end
 end
end
function T.stopAll()
 local restored=T.disable('health');T.disable('ammo')
 if not restored then return false,T.health.status end
 T.stopped=true;T.timer.Enabled=false;T.timer.destroy();T.timer=nil
 if VRMToggles==T then VRMToggles=nil end
 return true
end
T.timer=createTimer(nil,false);T.timer.Interval=50;T.timer.OnTimer=T.tick;T.timer.Enabled=true
VRMToggles=T
return T
]====]):sub(2),
 [ [====[VR-Missions/vrm-unlocks.lua]====] ]=([====[!-- US VR Missions menu access only. No completion flags, times or saves edited.
if VRMUnlocks then
 assert(VRMUnlocks.pid==getOpenedProcessID(),'Stop the previous unlock controller before changing processes')
 return VRMUnlocks
end
local dir=assert(debug.getinfo(1,'S').source:match('^@(.*[\\/])'))
local R=VRMReader
if not R or R.pid~=getOpenedProcessID()then R=dofile(dir..'vrm-reader.lua')end
local U={pid=R.pid,enabled=false,wanted=false,status='OFF',reader=R,version=1}
local MASK=0x40000000
local GROUPS=0xD0E08
local function u32(a)return assert(readInteger(a),'Menu word unavailable')&amp;0xFFFFFFFF end
local function u16(a)return assert(readSmallInteger(a),'Menu short unavailable')&amp;0xFFFF end
local function psx(p,n)
 assert(p&gt;=0x80000000 and p+(n or 1)&lt;=0x80200000,'Menu pointer outside RAM')
 return p&amp;0x1FFFFF
end
local function fp(r,o,hex)
 local expected=hex:gsub('%x%x',function(v)return string.char(tonumber(v,16))end)
 local b=assert(readBytes(r+o,#expected,true),'Menu code unavailable')
 assert(#b==#expected and string.char(table.unpack(b))==expected,'Unsupported VR menu code at '..string.format('%X',o))
end
function U.context()
 assert(getOpenedProcessID()==U.pid and process=='METAL GEAR SOLID.exe','Attached process changed')
 assert(getModuleSize(process)==30007296 and readQword(R.owner)==R.vtable,'Emulator owner differs')
 local r=readQword(R.owner+0x28)
 assert(r and readString(r+0x10000,11)=='SLUS_009.57','US VR Missions guest required')
 local stage=readString(r+0xB5B98,16)
 if stage~='selectvr'then return nil,'Outside mission-select menu'end
 assert(u32(r+0xAC1E8)==0,'Mission-select menu is loading')
 -- Confirm handler tests availability; renderer tests the same bit.
 fp(r,0xE0EC0,'0000638C0040023C24106200070040140020023C')
 fp(r,0xDDEEC,'0000A28C0040033C241043001000401058002925')
 -- Normal progression unlocks Special by ORing availability into root+0xB4.
 fp(r,0xDF6E0,'080E63240800648C00000000B400828C0040053C25104500B40082AC')
 -- Native header lookup uses 28-byte groups and group+8 child pointers.
 fp(r,0xDA180,'0D80023C080E4224C01804002318640080180300211862000400628C0800648C')
 local root=0xADA28
 for level=0,8 do
  local head=root+level*0x44;local tail=head+0x20
  assert(u32(r+head)==0 and u32(r+head+8)==0 and u32(r+head+12)==0 and u32(r+tail+4)==0 and u32(r+tail+8)==0 and u32(r+tail+12)==0,'Resident actor sentinels differ')
 end
 local head=root+7*0x44;local previous=head;local pointer=u32(r+head+4)
 local seen,managers={},{}
 for n=1,128 do
  local w=psx(pointer,0x374)
  if w==head+0x20 then assert(u32(r+w)==0x80000000+previous,'Menu actor tail changed');break end
  assert(not seen[w]and u32(r+w)==0x80000000+previous,'Menu actor list changed');seen[w]=true
  local np=u32(r+w+20)
  if np&gt;=0x80000000 and np&lt;0x80200000 and readString(r+psx(np),32)=='winmngr.c'then
   assert(u32(r+w+8)==0x800E17DC and u32(r+w+12)==0x800E2384,'Menu actor callbacks differ')
   managers[#managers+1]={work=w,namePointer=np}
  end
  previous=w;pointer=u32(r+w+4);assert(n&lt;128,'Menu actor count exceeds limit')
 end
 assert(#managers==1,'Expected one live mission-select manager')
 local manager=managers[1]
 local group=u16(r+manager.work+0x2CE)
 assert(group&lt;=70,'Menu navigation group differs')
 local c={ram=r,stage=stage,manager=manager,group=group,fields={},groups={}}
 local targets={}
 local function add(o,g,index)
  assert(not targets[o],'Overlapping menu options');targets[o]=true
  local flags=u32(r+o)
  assert(flags&amp;0x80000000~=0,'Menu option header differs')
  local art=u32(r+o+4);psx(art,4)
  c.fields[#c.fields+1]={offset=o,flags=flags,art=art,group=g,index=index}
 end
 assert(u32(r+GROUPS+4)==6 and u32(r+GROUPS+8)==0x800C5438,'Main category table differs')
 local entries=psx(u32(r+GROUPS+8),6*0x3C)
 for _,target in ipairs({{index=2,name='advanced_mode',destination=3},{index=3,name='special_mode',destination=4}})do
  local o=entries+target.index*0x3C
  local art=u32(r+o+4);local name=u32(r+psx(art,4))
  assert(readString(r+psx(name,1),32)==target.name,'Category name differs')
  assert(u16(r+o+0x22)==target.destination,'Category destination differs')
  add(o,0,target.index)
 end
 for g=0,70 do
  local o=GROUPS+g*0x1C
  local count,pointer,meta=u32(r+o+4),u32(r+o+8),u32(r+o+12)
  assert(count&gt;=1 and count&lt;=15,'Unexpected menu group size')
  local first=psx(pointer,count*0x3C)
  assert(first&gt;=0xC0000 and first+count*0x3C&lt;=0xD0E08,'Menu option array differs')
  local parent=meta&amp;0xFFFF
  if g==3 or g==4 or parent==3 or parent==4 then
   c.groups[#c.groups+1]={index=g,offset=o,count=count,pointer=pointer,meta=meta}
   for i=0,count-1 do add(first+i*0x3C,g,i)end
  end
 end
 assert(#c.groups==37 and #c.fields==198,'Unexpected Advanced/Special menu structure')
 c.epoch=tostring(r)..':'..manager.work..':'..manager.namePointer
 return c
end
local function put(r,o,v)
 assert(writeInteger(r+o,v&amp;0xFFFFFFFF),'Menu access write failed')
 assert(u32(r+o)&amp;MASK==v&amp;MASK,'Menu access verification failed')
end
function U.apply()
 local c,why=U.context()
 if not c then U.snapshot=nil;U.enabled=false;U.status='WAITING: '..why;return false end
 local fresh=U.context()
 assert(fresh and fresh.epoch==c.epoch,'Menu changed during access preflight')
 local s=U.snapshot
 if not s or s.epoch~=c.epoch then s={epoch=c.epoch,ram=c.ram,original={},identity={}};U.snapshot=s end
 -- Validate the complete plan before the first write.
 for _,v in ipairs(c.fields)do
  assert(u32(c.ram+v.offset+4)==v.art and u32(c.ram+v.offset)==v.flags,'Menu options changed')
  if s.identity[v.offset]then assert(s.identity[v.offset]==v.art,'Menu option identity changed')
  else s.identity[v.offset]=v.art;s.original[v.offset]=v.flags&amp;MASK end
 end
 local changed=0
 for _,v in ipairs(c.fields)do
  if v.flags&amp;MASK==0 then put(c.ram,v.offset,u32(c.ram+v.offset)|MASK);changed=changed+1 end
 end
 U.enabled=true;U.count=#c.fields;U.changed=changed;U.stage=c.stage
 U.status='ON - Advanced + Special access | '..#c.fields..' menu options | records unchanged'
 return true
end
function U.enable()
 assert(not U.stopped,'Reload the stopped unlock controller')
 if U.wanted then return true end
 local c,why=U.context();assert(c,why)
 U.wanted=true
 local ok,err=pcall(U.apply)
 if not ok then
  U.wanted=false;U.enabled=false
  local restored,cleanup=pcall(U.disable)
  U.status=(restored and cleanup)and ('ERROR: '..tostring(err))or ('CLEANUP WAITING: '..tostring(err))
  error(U.status)
 end
 if not U.timer then U.timer=createTimer(nil,false);U.timer.Interval=1000;U.timer.OnTimer=U.tick end
 U.timer.Enabled=true
 return true
end
function U.disable()
 U.wanted=false;U.enabled=false
 if U.timer then U.timer.Enabled=false end
 if U.snapshot then
  local ok,c=pcall(U.context)
  if not ok then U.status='CLEANUP WAITING: '..tostring(c);return false,U.status end
  if c and c.epoch==U.snapshot.epoch then
   for _,v in ipairs(c.fields)do
    local original=U.snapshot.original[v.offset]
    assert(original~=nil and U.snapshot.identity[v.offset]==v.art,'Menu restoration identity differs')
    put(c.ram,v.offset,(u32(c.ram+v.offset)&amp;(~MASK&amp;0xFFFFFFFF))|original)
   end
  end
 end
 U.snapshot=nil;U.status='OFF';return true
end
function U.tick()
 if not U.wanted then return end
 if getOpenedProcessID()~=U.pid then
  U.wanted=false;U.enabled=false;U.snapshot=nil
  U.timer.Enabled=false;U.status='Stopped: attached process changed';return
 end
 local ok,err=pcall(U.apply)
 if not ok then U.enabled=false;U.status='WAITING: '..tostring(err)end
end
function U.stop()
 local ok,err=U.disable();if not ok then return false,err end
 if U.timer then U.timer.destroy();U.timer=nil end
 U.stopped=true;if VRMUnlocks==U then VRMUnlocks=nil end;return true
end
VRMUnlocks=U
return U
]====]):sub(2),
}
for name,source in pairs(files)do
 assert(not name:find('..',1,true)and name:sub(1,1)~='/'and name:byte(1)~=92 and not name:find(':',1,true),'Invalid embedded path')
 local f=assert(io.open(root..'Table/'..name,'wb'),'Cannot extract bundled Lua: '..name)
 local ok,err=f:write(source);f:close();assert(ok,err)
end
MGSBundle={version=1,id='37e9633c62db3b08',root=root,dirs={mgs=root..'Table/',vr=root..'Table/VR-Missions/',integral=root..'Table/Integral/',special=root..'Table/Special-Missions/'}}
MGSTableDir=MGSBundle.dirs.mgs;VRMTableDir=MGSBundle.dirs.vr
INTTableDir=MGSBundle.dirs.integral;SPMTableDir=MGSBundle.dirs.special
</LuaScript>
</CheatTable>