deadbyte-mcp 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/MANIFEST.SHA256 +54 -36
  2. package/R41-PARENT.json +15 -0
  3. package/README.txt +2 -2
  4. package/bin/appcontainer-stage.obj +0 -0
  5. package/bin/bootstrap-advapi32.obj +0 -0
  6. package/bin/bootstrap-exitcode.obj +0 -0
  7. package/bin/bootstrap-kernel32.obj +0 -0
  8. package/bin/child-control-probe.obj +0 -0
  9. package/bin/child-control-stage.obj +0 -0
  10. package/bin/contained-reverse-worker.obj +0 -0
  11. package/bin/contained-transform-worker.obj +0 -0
  12. package/bin/containment-probe.obj +0 -0
  13. package/bin/deadbyte-contain.obj +0 -0
  14. package/bin/deadbyte-exec.obj +0 -0
  15. package/bin/deadbyte-process-host.obj +0 -0
  16. package/bin/deadbyte-tunnel-host.obj +0 -0
  17. package/controller/README.TXT +1 -1
  18. package/controller/deadbyte-controller.ps1 +1 -1
  19. package/controller/deadbyte-desktop-policy.json +5 -5
  20. package/controller/deadbyte-process-policy.json +4 -4
  21. package/docs/ARCHITECTURE.md +1 -1
  22. package/docs/superpowers/specs/2026-09-20-r41-deterministic-memory-design.md +132 -0
  23. package/package.json +8 -6
  24. package/proof/CONTAINMENT-BUILD.txt +6 -6
  25. package/scripts/build-containment.ps1 +24 -14
  26. package/scripts/build-desktop-r40.ps1 +15 -9
  27. package/scripts/deferred-slot-operation-r41.mjs +127 -0
  28. package/scripts/final-closure-r41.mjs +116 -0
  29. package/scripts/final-closure-verify-r41.mjs +215 -0
  30. package/scripts/gate-windows-r41.ps1 +48 -0
  31. package/scripts/init-desktop-policy-r40.ps1 +10 -4
  32. package/scripts/release-parity-r41.mjs +221 -0
  33. package/scripts/release-parity-tests-r41.ps1 +9 -0
  34. package/scripts/verify-memory-r41.mjs +88 -0
  35. package/scripts/verify-r41-parent.mjs +61 -0
  36. package/scripts/windows-gate-evidence-r41.mjs +53 -0
  37. package/src/autonomous-context-engine.mjs +2 -1
  38. package/src/autonomous-planner.mjs +2 -0
  39. package/src/autonomous-runtime.mjs +28 -9
  40. package/src/mcp-server.mjs +14 -1
  41. package/src/memory-r41.mjs +692 -0
  42. package/src/version.mjs +1 -1
  43. package/test/cli-entrypoint.test.mjs +1 -1
  44. package/test/controller-desktop-r40.test.mjs +2 -1
  45. package/test/core.test.mjs +1 -1
  46. package/test/helpers/autonomous-r34-fixture.mjs +3 -3
  47. package/test/memory-autonomous-integration-r41.test.mjs +31 -0
  48. package/test/memory-history-r41.test.mjs +126 -0
  49. package/test/memory-projections-r41.test.mjs +92 -0
  50. package/test/memory-retrieval-r41.test.mjs +124 -0
  51. package/test/memory-snapshot-r41.test.mjs +106 -0
  52. package/test/r33-closeout-regression.test.mjs +7 -7
  53. package/test/r33-finalization.test.mjs +4 -4
  54. package/test/r41-finalization.test.mjs +38 -0
  55. package/test/release-version.test.mjs +14 -13
@@ -0,0 +1,48 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ Set-StrictMode -Version 2.0
3
+
4
+ function Invoke-GateStep {
5
+ param(
6
+ [Parameter(Mandatory = $true)][string]$Name,
7
+ [Parameter(Mandatory = $true)][string[]]$NpmArgs
8
+ )
9
+ Write-Host "==== $Name ===="
10
+ & npm.cmd @NpmArgs
11
+ if ($LASTEXITCODE -ne 0) {
12
+ throw "DEADBYTE V0.13.0 / R41 gate failed at $Name with exit code $LASTEXITCODE"
13
+ }
14
+ }
15
+
16
+ Invoke-GateStep -Name 'r41-parent-verify' -NpmArgs @('run', 'r41:parent:verify')
17
+ Invoke-GateStep -Name 'containment-build' -NpmArgs @('run', 'containment:build')
18
+ Invoke-GateStep -Name 'process-policy-refresh' -NpmArgs @('run', 'process:policy:refresh')
19
+ Invoke-GateStep -Name 'desktop-policy-refresh' -NpmArgs @('run', 'desktop:policy:refresh')
20
+ Invoke-GateStep -Name 'release-manifest-write' -NpmArgs @('run', 'manifest:write')
21
+ Invoke-GateStep -Name 'release-manifest' -NpmArgs @('run', 'manifest:verify')
22
+ Write-Host '==== r41-memory-focused ===='
23
+ & node.exe --test test\memory-snapshot-r41.test.mjs test\memory-projections-r41.test.mjs test\memory-retrieval-r41.test.mjs test\memory-history-r41.test.mjs test\memory-autonomous-integration-r41.test.mjs
24
+ if ($LASTEXITCODE -ne 0) { throw "DEADBYTE V0.13.0 / R41 gate failed at r41-memory-focused with exit code $LASTEXITCODE" }
25
+ Invoke-GateStep -Name 'tests' -NpmArgs @('test')
26
+ Invoke-GateStep -Name 'mcp-smoke' -NpmArgs @('run', 'mcp:smoke')
27
+ Invoke-GateStep -Name 'mcp-agent-smoke' -NpmArgs @('run', 'mcp:agent:smoke')
28
+ Invoke-GateStep -Name 'mcp-coding-smoke' -NpmArgs @('run', 'mcp:coding:smoke')
29
+ Invoke-GateStep -Name 'mcp-machine-fs-smoke' -NpmArgs @('run', 'mcp:machine-fs:smoke')
30
+ Invoke-GateStep -Name 'mcp-observation-smoke' -NpmArgs @('run', 'mcp:observation:smoke')
31
+ Invoke-GateStep -Name 'mcp-process-smoke' -NpmArgs @('run', 'mcp:process:smoke')
32
+ Invoke-GateStep -Name 'mcp-autonomous-smoke' -NpmArgs @('run', 'mcp:autonomous:smoke')
33
+ Invoke-GateStep -Name 'tunnel-stdio-compat-smoke' -NpmArgs @('run', 'mcp:tunnel-compat:smoke')
34
+ Invoke-GateStep -Name 'mcp-host-smoke' -NpmArgs @('run', 'mcp:host:smoke')
35
+ Invoke-GateStep -Name 'authority-smoke' -NpmArgs @('run', 'authority:smoke')
36
+ Invoke-GateStep -Name 'containment-smoke' -NpmArgs @('run', 'containment:smoke')
37
+ Invoke-GateStep -Name 'contained-smoke' -NpmArgs @('run', 'contained:smoke')
38
+ Invoke-GateStep -Name 'mcp-contained-smoke' -NpmArgs @('run', 'mcp:contained:smoke')
39
+ Invoke-GateStep -Name 'release-manifest-final' -NpmArgs @('run', 'manifest:verify')
40
+
41
+ Write-Host '==== windows-gate-evidence ===='
42
+ & node.exe (Join-Path $PSScriptRoot 'windows-gate-evidence-r41.mjs')
43
+ if ($LASTEXITCODE -ne 0) {
44
+ throw "DEADBYTE V0.13.0 / R41 gate failed at windows-gate-evidence with exit code $LASTEXITCODE"
45
+ }
46
+
47
+ Write-Host '==== DEADBYTE V0.13.0 / R41 WINDOWS BATCH GATE: PASS ===='
48
+
@@ -6,6 +6,12 @@ param(
6
6
  )
7
7
  $ErrorActionPreference='Stop'
8
8
  Set-StrictMode -Version Latest
9
+ function Get-Sha256Hex {
10
+ param([Parameter(Mandatory=$true)][string]$Path)
11
+ $Stream=[System.IO.File]::OpenRead([System.IO.Path]::GetFullPath($Path))
12
+ try{$Hasher=[System.Security.Cryptography.SHA256]::Create();try{return ([System.BitConverter]::ToString($Hasher.ComputeHash($Stream))).Replace('-','').ToLowerInvariant()}finally{$Hasher.Dispose()}}
13
+ finally{$Stream.Dispose()}
14
+ }
9
15
 
10
16
  $Root=Split-Path -Parent $PSScriptRoot
11
17
  $Controller=Join-Path $Root 'controller'
@@ -35,16 +41,16 @@ $Policy=[ordered]@{
35
41
  evidence_dir=$Evidence
36
42
  observer=[ordered]@{
37
43
  executable=$Observer
38
- sha256=(Get-FileHash -LiteralPath $Observer -Algorithm SHA256).Hash.ToLowerInvariant()
44
+ sha256=Get-Sha256Hex -Path $Observer
39
45
  backend='gdi-bitblt-fallback'
40
46
  }
41
47
  input=[ordered]@{
42
48
  executable=$Input
43
- sha256=(Get-FileHash -LiteralPath $Input -Algorithm SHA256).Hash.ToLowerInvariant()
49
+ sha256=Get-Sha256Hex -Path $Input
44
50
  }
45
51
  grounder=[ordered]@{
46
52
  executable=$Grounder
47
- sha256=(Get-FileHash -LiteralPath $Grounder -Algorithm SHA256).Hash.ToLowerInvariant()
53
+ sha256=Get-Sha256Hex -Path $Grounder
48
54
  }
49
55
  allowed_input_desktops=@('Default')
50
56
  allowed_actions=@($AllowedActions)
@@ -69,7 +75,7 @@ Move-Item -LiteralPath $Tmp -Destination $OutputPath -Force
69
75
  [pscustomobject]@{
70
76
  status='created'
71
77
  policy_path=$OutputPath
72
- policy_sha256=(Get-FileHash -LiteralPath $OutputPath -Algorithm SHA256).Hash.ToLowerInvariant()
78
+ policy_sha256=Get-Sha256Hex -Path $OutputPath
73
79
  observer_sha256=$Policy.observer.sha256
74
80
  input_sha256=$Policy.input.sha256
75
81
  grounder_sha256=$Policy.grounder.sha256
@@ -0,0 +1,221 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
3
+ import { loadPowerShellDataFile } from '../src/runtime-update.mjs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { spawn } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { probeR40FullSurface } from '../src/r40-full-surface-probe.mjs';
9
+ import { runR40CompactParity } from '../src/remote-mcp-r40-parity-client.mjs';
10
+ import { probeR40CompactDisarmed } from '../src/r40-compact-disarmed-probe.mjs';
11
+ import { probeR36CompactDisarmed } from '../src/r36-compact-disarmed-probe.mjs';
12
+ import { runR40DesktopGuardedSmoke } from '../src/remote-mcp-desktop-r40-smoke-client.mjs';
13
+ import { verifyR41Memory } from './verify-memory-r41.mjs';
14
+
15
+ const here=path.dirname(fileURLToPath(import.meta.url));
16
+ const root=path.resolve(here,'..');
17
+ const stateRoot=path.resolve(process.env.DEADBYTE_STATE_ROOT||path.join(os.homedir(),'.deadbyte-mcp'));
18
+ const deferred=path.join(root,'scripts','deferred-slot-operation-r41.mjs');
19
+ const ps='C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
20
+ const launcher=path.join(stateRoot,'bin','DEADBYTE-MCP.ps1');
21
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
22
+ const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
23
+
24
+ export const R41_PREDECESSOR_RELEASE_ID='v0.12.0-70906ae0a7e4f062';
25
+ export const R41_PREDECESSOR_MANIFEST='70906ae0a7e4f0627efbb5087b40b85677c81ed6d64ed89c0ba2af846e390f39';
26
+
27
+ function assert(condition,message){if(!condition) throw new Error(message);}
28
+ function parseFrozenManifest(text){
29
+ const entries=[];const seen=new Set();
30
+ for(const [index,line] of text.split(/\r?\n/).entries()){
31
+ if(!line) continue;
32
+ const match=/^([0-9a-f]{64}) ([^\0]+)$/.exec(line);
33
+ assert(match,`frozen manifest line ${index+1} malformed`);
34
+ const rel=match[2];
35
+ assert(!path.posix.isAbsolute(rel)&&!rel.split('/').includes('..')&&!seen.has(rel),`unsafe/duplicate frozen manifest path: ${rel}`);
36
+ seen.add(rel);entries.push({sha256:match[1],path:rel});
37
+ }
38
+ return entries;
39
+ }
40
+ // Restore the mutable development stage from the immutable active release after live parity work may drift it.
41
+ export async function restoreFrozenStage({developmentRoot,releaseRoot,expectedManifestSha256}){
42
+ const dev=path.resolve(developmentRoot);const release=path.resolve(releaseRoot);
43
+ const manifestBytes=await readFile(path.join(release,'MANIFEST.SHA256'));
44
+ const manifestSha256=sha256(manifestBytes);
45
+ assert(manifestSha256===expectedManifestSha256,`immutable release manifest drift: ${manifestSha256}`);
46
+ const entries=parseFrozenManifest(manifestBytes.toString('utf8'));
47
+ for(const entry of entries){
48
+ const source=path.join(release,...entry.path.split('/'));const bytes=await readFile(source);
49
+ assert(sha256(bytes)===entry.sha256,`immutable release file drift: ${entry.path}`);
50
+ const destination=path.join(dev,...entry.path.split('/'));await mkdir(path.dirname(destination),{recursive:true});
51
+ await writeFile(destination,bytes);assert(sha256(await readFile(destination))===entry.sha256,`development restore verification failed: ${entry.path}`);
52
+ }
53
+ await writeFile(path.join(dev,'MANIFEST.SHA256'),manifestBytes);
54
+ assert(sha256(await readFile(path.join(dev,'MANIFEST.SHA256')))===expectedManifestSha256,'development manifest restore verification failed');
55
+ return {status:'restored',file_count:entries.length,manifest_sha256:manifestSha256};
56
+ }
57
+ function parseJsonOutput(text,label){
58
+ const trimmed=String(text).trim();const starts=[...trimmed.matchAll(/\{/g)].map(match=>match.index);
59
+ for(const start of starts){try{return JSON.parse(trimmed.slice(start));}catch{}}
60
+ throw new Error(`${label} did not emit JSON`);
61
+ }
62
+ function run(command,args,{timeoutMs=900000,env=process.env,cwd=root}={}){
63
+ return new Promise((resolve,reject)=>{
64
+ const child=spawn(command,args,{cwd,shell:false,windowsHide:true,env,stdio:['ignore','pipe','pipe']});
65
+ const out=[],err=[];const timer=setTimeout(()=>{child.kill();reject(new Error(`command timeout: ${path.basename(command)}`));},timeoutMs);
66
+ child.stdout.on('data',chunk=>out.push(Buffer.from(chunk)));child.stderr.on('data',chunk=>err.push(Buffer.from(chunk)));
67
+ child.on('error',error=>{clearTimeout(timer);reject(error);});child.on('exit',code=>{
68
+ clearTimeout(timer);const stdout=Buffer.concat(out).toString('utf8');const stderr=Buffer.concat(err).toString('utf8');
69
+ if(code!==0) reject(new Error(`command failed exit=${code}: ${stderr||stdout}`));else resolve({stdout,stderr,exitCode:code});
70
+ });
71
+ });
72
+ }
73
+ async function publicUrl(){
74
+ const value=(await readFile(path.join(stateRoot,'bridge','mcp-url.txt'),'utf8')).trim();const url=new URL(value);
75
+ if(url.protocol!=='https:') throw new Error('public MCP URL must be HTTPS');return value;
76
+ }
77
+ async function pointer(){return JSON.parse(await readFile(path.join(stateRoot,'active-release.json'),'utf8'));}
78
+ async function disarmAll(){
79
+ for(const command of ['disarmdesktop','disarmautonomous','disarmcoding','disarmprocess','disarmhost']){
80
+ await run(ps,['-NoLogo','-NoProfile','-ExecutionPolicy','Bypass','-File',launcher,command],{timeoutMs:60000});
81
+ }
82
+ }
83
+ async function waitDeferred(statePath,timeoutMs=180000){
84
+ const deadline=Date.now()+timeoutMs;
85
+ while(Date.now()<deadline){const state=JSON.parse(await readFile(statePath,'utf8'));if(state.state==='completed') return state;if(state.state==='failed') throw new Error(`deferred ${state.mode} failed: ${state.error}`);await sleep(500);}
86
+ throw new Error(`deferred operation timeout: ${statePath}`);
87
+ }
88
+ async function scheduleDeferred(mode,value,{bridgeRoot=null,bridgeScriptSha256=null}={}){
89
+ if((bridgeRoot===null)!==(bridgeScriptSha256===null)) throw new Error('deferred bridge override requires exact root + SHA pair');
90
+ const args=[deferred,mode,value];
91
+ if(bridgeRoot!==null) args.push('--bridge-root',bridgeRoot,'--bridge-script-sha256',bridgeScriptSha256);
92
+ const scheduled=parseJsonOutput((await run(process.execPath,args,{timeoutMs:30000})).stdout,`deferred ${mode}`);
93
+ assert(scheduled.status==='scheduled',`deferred ${mode} was not scheduled`);
94
+ assert(scheduled.execution_provider==='deadbyte_mcp'&&scheduled.rdc_operation_count===0,'deferred operation provider mismatch');
95
+ return {scheduled,completed:await waitDeferred(scheduled.state_path)};
96
+ }
97
+ async function publicR40PredecessorDisarmed(url){
98
+ const result=await probeR36CompactDisarmed(url);
99
+ assert(result.status==='passed'&&result.tool_count<=42&&result.capability_closure===true,'R40 predecessor public compact catalog mismatch');
100
+ assert(result.release_id===R41_PREDECESSOR_RELEASE_ID&&result.release_manifest_sha256===R41_PREDECESSOR_MANIFEST,'R40 predecessor machine binding mismatch');
101
+ assert(result.coding_armed===false&&result.autonomous_armed===false,'R40 predecessor authority remained armed');
102
+ return result;
103
+ }
104
+ async function mutableCore(pointerValue){
105
+ const policy=JSON.parse(await readFile(path.join(pointerValue.generation_root,'coding-policy.json'),'utf8'));
106
+ const raw=policy?.roots?.core?.path??policy?.roots?.core?.real_path;
107
+ assert(typeof raw==='string'&&raw,'R40 generation missing coding core root');
108
+ const core=path.resolve(raw);const release=path.resolve(pointerValue.release_root);
109
+ assert(core.toLowerCase()!==release.toLowerCase(),'R40 coding core must not point at immutable active release slot');
110
+ return core;
111
+ }
112
+
113
+ export function validateParityEvidence(value){
114
+ assert(value?.schema==='deadbyte.r41-parity.v1','R40 parity schema mismatch');
115
+ assert(value.status==='passed','R40 parity status is not passed');
116
+ assert(value.rdc_operation_count===0&&value.execution_provider==='deadbyte_mcp','R40 parity used non-DEADBYTE execution');
117
+ assert(value.candidate?.version==='0.13.0'&&/^[0-9a-f]{64}$/.test(value.candidate?.manifest_sha256??''),'R40 candidate identity missing');
118
+ assert(value.local_full?.status==='passed'&&value.local_full?.tool_count===80&&value.local_full?.strict_output_schemas===true,'R40 local full 80-tool proof missing');
119
+ assert(value.public_compact?.status==='passed'&&value.public_compact?.tool_count===42&&value.public_compact?.capability_closure===true&&value.public_compact?.gateway_count===6&&value.public_compact?.desktop_armed===false&&value.public_compact?.desktop_observation_receipt_verified===true&&value.public_compact?.desktop_grounding_receipt_verified===true,'R40 public compact/Desktop closure missing');
120
+ assert(value.desktop_guarded?.status==='passed'&&value.desktop_guarded?.native_injected===true&&value.desktop_guarded?.replay_performed===false&&
121
+ Number.isInteger(value.desktop_guarded?.predispatch_retry_count)&&value.desktop_guarded.predispatch_retry_count>=0&&value.desktop_guarded.predispatch_retry_count<=2&&
122
+ value.desktop_guarded?.observation_receipts_verified===value.desktop_guarded.predispatch_retry_count+1&&value.desktop_guarded?.action_receipts_verified===3,
123
+ 'R40 guarded Desktop proof missing');
124
+ assert(value.autonomous?.status==='passed'&&value.autonomous?.signed_release_verified===true,'R40 autonomous live proof missing');
125
+ assert(value.deterministic_memory?.status==='passed'&&value.deterministic_memory?.goal_count>=1&&value.deterministic_memory?.snapshot_count>=1&&value.deterministic_memory?.index_count>=1,'R41 deterministic memory proof missing');
126
+ assert(value.before_rollback_disarmed?.status==='passed'&&value.before_rollback_disarmed?.capability_closure===true&&value.before_rollback_disarmed?.coding_armed===false&&value.before_rollback_disarmed?.autonomous_armed===false&&value.before_rollback_disarmed?.desktop_armed===false,'R40 pre-rollback disarm proof missing');
127
+ assert(value.rollback?.state==='completed'&&value.restore?.state==='completed','R40 rollback/restore not completed');
128
+ assert(value.stage_restore?.status==='restored'&&value.stage_restore?.manifest_sha256===value.candidate.manifest_sha256,'R40 stage restore proof missing');
129
+ assert(value.predecessor?.release_id===R41_PREDECESSOR_RELEASE_ID&&value.predecessor?.manifest_sha256===R41_PREDECESSOR_MANIFEST&&value.predecessor?.version==='0.12.0','R40 exact predecessor identity mismatch');
130
+ assert(value.predecessor_disarmed?.status==='passed'&&value.predecessor_disarmed?.tool_count<=42&&value.predecessor_disarmed?.capability_closure===true,'R40 predecessor public proof missing');
131
+ assert(value.successor?.version==='0.13.0'&&value.successor?.manifest_sha256===value.candidate.manifest_sha256,'R40 exact successor restore identity mismatch');
132
+ assert(value.successor_disarmed?.status==='passed'&&value.successor_disarmed?.capability_closure===true&&value.successor_disarmed?.coding_armed===false&&value.successor_disarmed?.autonomous_armed===false&&value.successor_disarmed?.desktop_armed===false,'R40 successor disarmed proof missing');
133
+ assert(value.immutable_slot?.protected===true&&value.immutable_slot?.development_root!==value.immutable_slot?.release_root,'R40 immutable-slot separation missing');
134
+ for(const key of ['tree_read','precondition_mutation','search','owned_process','observation','coding_loop','autonomy','interrupted_recovery','evidence_verification','compact_closure','full_surface','desktop_readonly','desktop_guarded_input','deterministic_memory']) assert(value.requirements?.[key]===true,`R41 parity requirement not proven: ${key}`);
135
+ return true;
136
+ }
137
+
138
+ export async function runReleaseParity(activationReceiptPath){
139
+ const active=await pointer();const candidateManifest=sha256(await readFile(path.join(root,'MANIFEST.SHA256')));
140
+ assert(active.version==='0.13.0','R41 parity requires active 0.13.0 candidate');
141
+ assert(active.manifest_sha256===candidateManifest,'active release is not canonical R40 candidate');
142
+ const activeConfig=await loadPowerShellDataFile(active.config_path);
143
+ const successorBridgeRootRaw=activeConfig?.Bridge?.WorkingDirectory;
144
+ const successorBridgeConfiguredSha=activeConfig?.Bridge?.ScriptSha256;
145
+ assert(typeof successorBridgeRootRaw==='string'&&path.isAbsolute(successorBridgeRootRaw),'R40 active bridge root missing');
146
+ assert(typeof successorBridgeConfiguredSha==='string'&&/^[0-9a-f]{64}$/.test(successorBridgeConfiguredSha),'R40 active bridge SHA missing');
147
+ const successorBridgeRoot=await realpath(path.resolve(successorBridgeRootRaw));
148
+ const successorBridgeActualSha=sha256(await readFile(path.join(successorBridgeRoot,'src','bridge.mjs')));
149
+ assert(successorBridgeActualSha===successorBridgeConfiguredSha,'R40 active bridge bytes do not match generation pin');
150
+ const successorBridge={root:successorBridgeRoot,sha256:successorBridgeActualSha};
151
+ const developmentRoot=await mutableCore(active);
152
+ const localFull=await probeR40FullSurface({packageRoot:active.release_root,generationRoot:active.generation_root,stateRoot});
153
+ const url=await publicUrl();
154
+ let publicCompact,autonomous,desktopGuarded;
155
+ try{
156
+ publicCompact=await runR40CompactParity(url);
157
+ autonomous=parseJsonOutput((await run(process.execPath,[path.join(root,'src','remote-mcp-autonomous-smoke-client.mjs'),url],{timeoutMs:900000})).stdout,'R40 autonomous compact parity');
158
+ assert(autonomous.status==='passed'&&autonomous.signed_release_verified===true,'R40 autonomous compact parity failed');
159
+ await run(ps,['-NoLogo','-NoProfile','-ExecutionPolicy','Bypass','-File',launcher,'armdesktop'],{timeoutMs:60000});
160
+ try{desktopGuarded=await runR40DesktopGuardedSmoke(url);}
161
+ finally{await run(ps,['-NoLogo','-NoProfile','-ExecutionPolicy','Bypass','-File',launcher,'disarmdesktop'],{timeoutMs:60000}).catch(()=>{});}
162
+ assert(desktopGuarded.status==='passed'&&desktopGuarded.native_injected===true&&desktopGuarded.action_receipts_verified===3,'R40 guarded Desktop public smoke failed');
163
+ }catch(error){await disarmAll().catch(()=>{});throw error;}
164
+ const deterministicMemory=await verifyR41Memory({memoryRoot:path.join(stateRoot,'evidence','autonomous','memory-r41',candidateManifest),
165
+ journalRoot:path.join(stateRoot,'evidence','autonomous','goals'),sourceReleaseManifest:candidateManifest,
166
+ publicKeyPath:path.join(stateRoot,'trust','ed25519-public.pem')});
167
+ assert(deterministicMemory.goal_count>=1&&deterministicMemory.snapshot_count>=1&&deterministicMemory.index_count>=1,'R41 live deterministic memory evidence missing');
168
+
169
+ await disarmAll();
170
+ const beforeRollback=await probeR40CompactDisarmed(url);
171
+ const rollbackPair=await scheduleDeferred('rollback',path.resolve(activationReceiptPath));
172
+ const predecessor=await pointer();
173
+ assert(predecessor.release_id===R41_PREDECESSOR_RELEASE_ID&&predecessor.manifest_sha256===R41_PREDECESSOR_MANIFEST&&predecessor.version==='0.12.0','rollback did not reach exact sealed R40 predecessor');
174
+ const predecessorDisarmed=await publicR40PredecessorDisarmed(url);
175
+ const stageRestore=await restoreFrozenStage({developmentRoot,releaseRoot:active.release_root,expectedManifestSha256:candidateManifest});
176
+ const restorePair=await scheduleDeferred('activate',candidateManifest,{bridgeRoot:successorBridge.root,bridgeScriptSha256:successorBridge.sha256});
177
+ const successor=await pointer();
178
+ assert(successor.version==='0.13.0'&&successor.manifest_sha256===candidateManifest,'restore did not return exact R40 candidate');
179
+ const successorDisarmed=await probeR40CompactDisarmed(url);
180
+ await disarmAll();
181
+
182
+ const evidence={
183
+ schema:'deadbyte.r41-parity.v1',status:'passed',completed_at_utc:new Date().toISOString(),execution_provider:'deadbyte_mcp',rdc_operation_count:0,
184
+ candidate:{release_id:active.release_id,version:active.version,manifest_sha256:candidateManifest},
185
+ immutable_slot:{protected:true,release_root:path.resolve(active.release_root),development_root:developmentRoot},
186
+ local_full:localFull,public_compact:publicCompact,autonomous,deterministic_memory:deterministicMemory,desktop_guarded:desktopGuarded,before_rollback_disarmed:beforeRollback,
187
+ rollback:{...rollbackPair.completed,scheduled_operation_id:rollbackPair.scheduled.operation_id},
188
+ predecessor:{release_id:predecessor.release_id,version:predecessor.version,manifest_sha256:predecessor.manifest_sha256},predecessor_disarmed:predecessorDisarmed,
189
+ stage_restore:stageRestore,
190
+ restore:{...restorePair.completed,scheduled_operation_id:restorePair.scheduled.operation_id},
191
+ successor:{release_id:successor.release_id,version:successor.version,manifest_sha256:successor.manifest_sha256},successor_disarmed:successorDisarmed,
192
+ requirements:{
193
+ tree_read:publicCompact.tree_entries>=0&&publicCompact.coding_stat_verified===true,
194
+ precondition_mutation:publicCompact.machine_fs_receipts_verified>=3,
195
+ search:publicCompact.coding_search_result_count>=1&&publicCompact.observation_search_result_count>=1,
196
+ owned_process:typeof publicCompact.process_session_id==='string'&&publicCompact.process_output_bytes>0,
197
+ observation:publicCompact.observation_receipts_verified>=2,
198
+ coding_loop:publicCompact.coding_receipts_verified===2,
199
+ autonomy:autonomous.signed_release_verified===true&&autonomous.observed_failure_before_replan===true,
200
+ interrupted_recovery:rollbackPair.completed.state==='completed'&&restorePair.completed.state==='completed',
201
+ evidence_verification:publicCompact.machine_fs_receipts_verified>=3&&autonomous.signed_release_verified===true,
202
+ compact_closure:publicCompact.capability_closure===true&&successorDisarmed.capability_closure===true,
203
+ full_surface:localFull.tool_count===80&&localFull.strict_output_schemas===true,
204
+ desktop_readonly:publicCompact.desktop_armed===false&&publicCompact.desktop_observation_receipt_verified===true&&publicCompact.desktop_grounding_receipt_verified===true,
205
+ desktop_guarded_input:desktopGuarded.native_injected===true&&desktopGuarded.replay_performed===false&&desktopGuarded.action_receipts_verified===3,
206
+ deterministic_memory:deterministicMemory.status==='passed'&&deterministicMemory.goal_count>=1&&deterministicMemory.snapshot_count>=1
207
+ }
208
+ };
209
+ validateParityEvidence(evidence);
210
+ const evidenceDir=path.join(stateRoot,'evidence','release');await mkdir(evidenceDir,{recursive:true});
211
+ const evidencePath=path.join(evidenceDir,`r41-parity-${candidateManifest.slice(0,16)}.json`);
212
+ const bytes=Buffer.from(`${JSON.stringify(evidence,null,2)}\n`,'utf8');await writeFile(evidencePath,bytes);
213
+ return {evidence,evidence_path:evidencePath,evidence_sha256:sha256(bytes)};
214
+ }
215
+
216
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
217
+ const receipt=process.argv[2];if(!receipt) throw new Error('usage: node scripts/release-parity-r41.mjs <activation-receipt.json>');
218
+ runReleaseParity(receipt).then(result=>console.log(JSON.stringify({status:'passed',...result},null,2))).catch(error=>{console.error(error instanceof Error?error.stack:String(error));process.exitCode=1;});
219
+ }
220
+
221
+
@@ -0,0 +1,9 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ Set-StrictMode -Version 2.0
3
+ $root = Split-Path -Parent $PSScriptRoot
4
+ Push-Location $root
5
+ try {
6
+ & node.exe --test test\memory-snapshot-r41.test.mjs test\memory-projections-r41.test.mjs test\memory-retrieval-r41.test.mjs test\memory-history-r41.test.mjs test\memory-autonomous-integration-r41.test.mjs test\r41-finalization.test.mjs test\controller.test.mjs test\controller-desktop-r40.test.mjs test\r40-finalization.test.mjs test\release-version.test.mjs test\desktop-contract-r40.test.mjs test\desktop-policy-r40.test.mjs test\desktop-observer-r40.test.mjs test\desktop-input-r40.test.mjs test\desktop-uia-r40.test.mjs test\desktop-runtime-r40.test.mjs test\desktop-memory-r40.test.mjs test\desktop-mcp-tools-r40.test.mjs test\desktop-adversarial-r40.test.mjs test\autonomous-desktop-r40.test.mjs test\release-generation.test.mjs test\runtime-self-update.test.mjs test\r37-0110-history.test.mjs test\r37-agent-fabric.test.mjs test\remote-live-log-r37.test.mjs test\remote-session-cli.test.mjs test\r36-finalization.test.mjs test\r36-release-identity.test.mjs test\deferred-slot-operation.test.mjs
7
+ if ($LASTEXITCODE -ne 0) { throw "R41 release parity tests failed with exit code $LASTEXITCODE" }
8
+ Write-Output 'R41 RELEASE PARITY TEST PASS'
9
+ } finally { Pop-Location }
@@ -0,0 +1,88 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile,readdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { canonicalJson } from '../src/canonical-json.mjs';
6
+ import { loadPublicVerifyKey } from '../src/trust.mjs';
7
+ import { buildMemoryArchive,buildMemoryCorpus,buildRetrievalIndex,verifyMemoryGoal,verifyMemoryJournal,
8
+ verifyMemorySnapshot,verifyRetrievalIndex } from '../src/memory-r41.mjs';
9
+
10
+ const HEX64=/^[0-9a-f]{64}$/;
11
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
12
+ const insist=(ok,message)=>{if(!ok)throw new Error(message);};
13
+ const readJson=async file=>JSON.parse((await readFile(file,'utf8')).replace(/^\uFEFF/,''));
14
+ async function jsonFiles(dir){return (await readdir(dir)).filter(name=>name.endsWith('.json')).sort();}
15
+ function parseArgs(argv){
16
+ const out={};for(let index=0;index<argv.length;index+=2){const key=argv[index];insist(key?.startsWith('--')&&argv[index+1],`invalid argument ${key??''}`);out[key.slice(2)]=argv[index+1];}
17
+ for(const key of ['memory-root','journal-root','manifest','public-key'])insist(out[key],`missing --${key}`);return out;
18
+ }
19
+ async function loadCanonicalGoal(journalRoot,goalId,publicKey,keyId,manifest){
20
+ const root=path.join(journalRoot,goalId);const goal=verifyMemoryGoal(await readJson(path.join(root,'goal.json')),{publicKey,keyId,expectedGoalId:goalId});
21
+ const names=await jsonFiles(path.join(root,'events'));
22
+ insist(names.every((name,index)=>name===`${String(index+1).padStart(6,'0')}.json`),`event gap for ${goalId}`);
23
+ const events=[];for(const name of names)events.push(await readJson(path.join(root,'events',name)));
24
+ verifyMemoryJournal(events,{goalId,publicKey,keyId});
25
+ insist(events[0]?.type==='goal_created'&&events[0]?.payload?.source_release_manifest===manifest,`goal ${goalId} is not bound to release manifest`);
26
+ return {goal,events,corpus:buildMemoryCorpus({goal,events,publicKey,keyId,sourceReleaseManifest:manifest})};
27
+ }
28
+
29
+ export async function verifyR41Memory({memoryRoot,journalRoot,sourceReleaseManifest,publicKeyPath}={}){
30
+ insist(path.isAbsolute(memoryRoot)&&path.isAbsolute(journalRoot),'memory verifier roots must be absolute');insist(HEX64.test(sourceReleaseManifest??''),'memory verifier manifest invalid');
31
+ const {publicKey,keyId}=await loadPublicVerifyKey(publicKeyPath);const canonical=new Map();let snapshots=0,indexes=0,archives=0,archiveIndexes=0;
32
+ let journalGoalIds=[];try{journalGoalIds=(await readdir(journalRoot,{withFileTypes:true})).filter(entry=>entry.isDirectory()&&HEX64.test(entry.name)).map(entry=>entry.name).sort();}
33
+ catch(error){if(error?.code!=='ENOENT')throw error;}
34
+ for(const goalId of journalGoalIds){
35
+ const firstPath=path.join(journalRoot,goalId,'events','000001.json');let first;
36
+ try{first=await readJson(firstPath);}catch(error){if(error?.code==='ENOENT')continue;throw error;}
37
+ verifyMemoryJournal([first],{goalId,publicKey,keyId});
38
+ if(first.type!=='goal_created'||first.payload?.source_release_manifest!==sourceReleaseManifest)continue;
39
+ const loaded=await loadCanonicalGoal(journalRoot,goalId,publicKey,keyId,sourceReleaseManifest);canonical.set(goalId,loaded);
40
+ }
41
+ let goalIds=[];try{goalIds=(await readdir(path.join(memoryRoot,'goals'),{withFileTypes:true})).filter(entry=>entry.isDirectory()&&HEX64.test(entry.name)).map(entry=>entry.name).sort();}
42
+ catch(error){if(error?.code!=='ENOENT')throw error;}
43
+ for(const goalId of goalIds){
44
+ const loaded=canonical.get(goalId);insist(loaded,`memory projection goal ${goalId} has no canonical release-bound journal`);
45
+ const base=path.join(memoryRoot,'goals',goalId);const corporaByMemoryHash=new Map();
46
+ for(const name of await jsonFiles(path.join(base,'snapshots'))){
47
+ const value=await readJson(path.join(base,'snapshots',name));
48
+ const proof=verifyMemorySnapshot(value,{goal:loaded.goal,events:loaded.events,publicKey,keyId,sourceReleaseManifest});
49
+ insist(proof.ok,`snapshot invalid ${goalId}/${name}: ${proof.reason}`);
50
+ const prefixEvents=loaded.events.slice(0,proof.last_event_seq);
51
+ const prefixCorpus=buildMemoryCorpus({goal:loaded.goal,events:prefixEvents,publicKey,keyId,sourceReleaseManifest});
52
+ const prior=corporaByMemoryHash.get(prefixCorpus.memory_sha256);
53
+ insist(!prior||canonicalJson(prior)===canonicalJson(prefixCorpus),`snapshot corpus collision ${goalId}/${name}`);
54
+ corporaByMemoryHash.set(prefixCorpus.memory_sha256,prefixCorpus);snapshots+=1;
55
+ }
56
+ for(const name of await jsonFiles(path.join(base,'indexes'))){
57
+ const value=await readJson(path.join(base,'indexes',name));
58
+ const sourceCorpus=corporaByMemoryHash.get(value.source_memory_sha256);
59
+ insist(sourceCorpus,`index source memory hash has no verified snapshot prefix ${goalId}/${name}`);
60
+ const proof=verifyRetrievalIndex(value,{corpus:sourceCorpus,sourceReleaseManifest});
61
+ insist(proof.ok,`index invalid ${goalId}/${name}: ${proof.reason}`);indexes+=1;
62
+ }
63
+ }
64
+ const archiveByHash=new Map();
65
+ try{for(const name of await jsonFiles(path.join(memoryRoot,'archives'))){const value=await readJson(path.join(memoryRoot,'archives',name));
66
+ const corpora=value.corpus_refs.map(ref=>{
67
+ const loaded=canonical.get(ref.goal_id);insist(loaded,`archive references noncanonical goal ${ref.goal_id}`);
68
+ const headIndex=loaded.events.findIndex(event=>event.event_sha256===ref.journal_head_sha256);
69
+ insist(headIndex>=0,`archive references unknown journal head ${ref.goal_id}`);
70
+ const corpus=buildMemoryCorpus({goal:loaded.goal,events:loaded.events.slice(0,headIndex+1),publicKey,keyId,sourceReleaseManifest});
71
+ insist(corpus.memory_sha256===ref.memory_sha256,`archive references noncanonical goal prefix ${ref.goal_id}`);
72
+ return corpus;
73
+ });
74
+ const expected=buildMemoryArchive(corpora,{sourceReleaseManifest});insist(canonicalJson(expected)===canonicalJson(value),'archive projection mismatch');insist(name===`${value.memory_sha256}.json`,'archive filename mismatch');archiveByHash.set(value.memory_sha256,value);archives+=1;}}
75
+ catch(error){if(error?.code!=='ENOENT')throw error;}
76
+ try{for(const name of await jsonFiles(path.join(memoryRoot,'archive-indexes'))){const value=await readJson(path.join(memoryRoot,'archive-indexes',name));const archive=archiveByHash.get(value.source_memory_sha256);insist(archive,'archive index source missing');
77
+ const proof=verifyRetrievalIndex(value,{corpus:archive,sourceReleaseManifest});insist(proof.ok,`archive index invalid ${name}: ${proof.reason}`);insist(canonicalJson(buildRetrievalIndex(archive,{sourceReleaseManifest}))===canonicalJson(value),'archive index rebuild mismatch');archiveIndexes+=1;}}
78
+ catch(error){if(error?.code!=='ENOENT')throw error;}
79
+ return {schema:'deadbyte.r41-memory-verification.v1',status:'passed',source_release_manifest:sourceReleaseManifest,
80
+ goal_count:goalIds.length,snapshot_count:snapshots,index_count:indexes,archive_count:archives,archive_index_count:archiveIndexes,
81
+ verification_sha256:sha(Buffer.from(canonicalJson({goalIds,snapshots,indexes,archives,archiveIndexes,sourceReleaseManifest}),'utf8'))};
82
+ }
83
+
84
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
85
+ const args=parseArgs(process.argv.slice(2));verifyR41Memory({memoryRoot:path.resolve(args['memory-root']),journalRoot:path.resolve(args['journal-root']),
86
+ sourceReleaseManifest:args.manifest,publicKeyPath:path.resolve(args['public-key'])}).then(result=>console.log(JSON.stringify(result,null,2)))
87
+ .catch(error=>{console.error(error instanceof Error?error.stack:String(error));process.exitCode=1;});
88
+ }
@@ -0,0 +1,61 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat,readFile,readdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
7
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
8
+ const insist=(ok,message)=>{if(!ok)throw new Error(message);};
9
+
10
+ function parseManifest(bytes){
11
+ const entries=new Map();
12
+ for(const [index,line] of bytes.toString('utf8').split(/\r?\n/).entries()){
13
+ if(!line)continue;
14
+ const match=/^([0-9a-f]{64}) ([^\0]+)$/.exec(line);insist(match,`parent manifest line ${index+1} malformed`);
15
+ const rel=match[2];insist(!path.posix.isAbsolute(rel)&&!rel.split('/').includes('..')&&!entries.has(rel),`unsafe/duplicate parent manifest path ${rel}`);
16
+ entries.set(rel,match[1]);
17
+ }
18
+ return entries;
19
+ }
20
+ async function walk(dir,rel=''){
21
+ const out=[];
22
+ for(const name of (await readdir(path.join(dir,...(rel?rel.split('/'):[])))).sort((a,b)=>a.localeCompare(b,'en'))){
23
+ const child=rel?`${rel}/${name}`:name;const full=path.join(dir,...child.split('/'));const st=await lstat(full);
24
+ insist(!st.isSymbolicLink(),`parent tree symlink forbidden: ${child}`);
25
+ if(st.isDirectory())out.push(...await walk(dir,child));else{insist(st.isFile(),`parent tree non-file forbidden: ${child}`);out.push(child);}
26
+ }
27
+ return out;
28
+ }
29
+ async function verifyTree(dir,expectedManifest,{exact}){
30
+ const bytes=await readFile(path.join(dir,'MANIFEST.SHA256'));insist(sha(bytes)===expectedManifest,`parent manifest digest mismatch: ${dir}`);
31
+ const entries=parseManifest(bytes);
32
+ if(exact){
33
+ const actual=(await walk(dir)).filter(rel=>rel!=='MANIFEST.SHA256');
34
+ insist(actual.length===entries.size&&actual.every(rel=>entries.has(rel)),`parent exact tree mismatch: ${dir}`);
35
+ }
36
+ for(const [rel,digest] of entries)insist(sha(await readFile(path.join(dir,...rel.split('/'))))===digest,`parent file hash mismatch: ${dir} :: ${rel}`);
37
+ return entries.size;
38
+ }
39
+
40
+ export async function verifyR41Parent(file=path.join(root,'R41-PARENT.json')){
41
+ const record=JSON.parse(await readFile(path.resolve(file),'utf8'));
42
+ insist(record.schema==='deadbyte.r41-parent.v1','R41 parent schema mismatch');
43
+ insist(record.parent_version==='0.12.0'&&record.parent_release_id==='v0.12.0-70906ae0a7e4f062','R41 parent identity mismatch');
44
+ const [sourceFiles,releaseFiles]=await Promise.all([
45
+ verifyTree(path.resolve(record.parent_source_root),record.parent_manifest_sha256,{exact:false}),
46
+ verifyTree(path.resolve(record.parent_release_root),record.parent_manifest_sha256,{exact:true})
47
+ ]);
48
+ insist(sourceFiles===record.parent_manifest_file_count&&releaseFiles===record.parent_manifest_file_count,'R41 parent file count mismatch');
49
+ const evidenceBytes=await readFile(path.resolve(record.parent_public_evidence_path));
50
+ insist(sha(evidenceBytes)===record.parent_public_evidence_sha256,'R40 public evidence hash mismatch');
51
+ const evidence=JSON.parse(evidenceBytes.toString('utf8').replace(/^\uFEFF/,''));
52
+ insist(evidence.schema==='deadbyte.r40-public-final-verify.v1'&&evidence.status==='passed','R40 public evidence status invalid');
53
+ insist(evidence.release_id===record.parent_release_id&&evidence.manifest_sha256===record.parent_manifest_sha256,'R40 public evidence identity mismatch');
54
+ return {status:'passed',parent_release_id:record.parent_release_id,parent_manifest_sha256:record.parent_manifest_sha256,
55
+ source_files:sourceFiles,release_files:releaseFiles,parent_public_evidence_sha256:record.parent_public_evidence_sha256};
56
+ }
57
+
58
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
59
+ verifyR41Parent(process.argv[2]).then(value=>console.log(JSON.stringify(value,null,2)))
60
+ .catch(error=>{console.error(error instanceof Error?error.stack:String(error));process.exitCode=1;});
61
+ }
@@ -0,0 +1,53 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, open, readFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const here=path.dirname(fileURLToPath(import.meta.url));
8
+ const root=path.resolve(here,'..');
9
+ const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
10
+ const marker='DEADBYTE V0.13.0 / R41 WINDOWS BATCH GATE: PASS';
11
+ function insist(ok,message){if(!ok) throw new Error(message);}
12
+
13
+ export async function writeWindowsGateEvidence({
14
+ candidateRoot=root,
15
+ stateRoot=path.resolve(process.env.DEADBYTE_STATE_ROOT||path.join(os.homedir(),'.deadbyte-mcp')),
16
+ clock=()=>new Date()
17
+ }={}){
18
+ const candidate=path.resolve(candidateRoot);
19
+ const manifestBytes=await readFile(path.join(candidate,'MANIFEST.SHA256'));
20
+ const manifestSha256=sha256(manifestBytes);
21
+ const pkg=JSON.parse(await readFile(path.join(candidate,'package.json'),'utf8'));
22
+ insist(pkg.version==='0.13.0',`Windows gate evidence requires V0.13.0, found ${pkg.version}`);
23
+ const completed=clock();
24
+ insist(completed instanceof Date&&!Number.isNaN(completed.getTime()),'Windows gate evidence clock invalid');
25
+ const evidence={
26
+ schema:'deadbyte.r41-windows-gate.v1',status:'passed',exit_code:0,version:'0.13.0',
27
+ marker,completed_at_utc:completed.toISOString(),manifest_sha256:manifestSha256
28
+ };
29
+ const bytes=Buffer.from(`${JSON.stringify(evidence,null,2)}\n`,'utf8');
30
+ const dir=path.join(path.resolve(stateRoot),'evidence','release');
31
+ await mkdir(dir,{recursive:true});
32
+ const file=path.join(dir,`r41-windows-gate-${manifestSha256.slice(0,16)}.json`);
33
+ try{
34
+ const handle=await open(file,'wx',0o600);
35
+ try{await handle.writeFile(bytes);await handle.sync();}finally{await handle.close();}
36
+ return {status:'written',path:file,sha256:sha256(bytes),manifest_sha256:manifestSha256};
37
+ }catch(error){
38
+ if(error?.code!=='EEXIST') throw error;
39
+ const existingBytes=await readFile(file);
40
+ const existing=JSON.parse(existingBytes.toString('utf8'));
41
+ insist(existing.schema===evidence.schema&&existing.status==='passed'&&existing.exit_code===0,'existing Windows gate evidence invalid');
42
+ insist(existing.version==='0.13.0'&&existing.marker===marker&&existing.manifest_sha256===manifestSha256,'existing Windows gate evidence binding mismatch');
43
+ return {status:'existing',path:file,sha256:sha256(existingBytes),manifest_sha256:manifestSha256};
44
+ }
45
+ }
46
+
47
+ const invoked=process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url);
48
+ if(invoked){
49
+ writeWindowsGateEvidence()
50
+ .then(result=>console.log(JSON.stringify(result)))
51
+ .catch(error=>{console.error(error instanceof Error?error.stack:String(error));process.exitCode=1;});
52
+ }
53
+
@@ -213,7 +213,7 @@ function historicalEvidence({ contexts, observations, loopState }) {
213
213
  };
214
214
  }
215
215
 
216
- export function buildLoopContext({ goal, policy, loopState = {}, tree = [], contexts = [], observations = [], decisions = [], projectMemory = null, desktopMemory = null, capabilities = null }) {
216
+ export function buildLoopContext({ goal, policy, loopState = {}, tree = [], contexts = [], observations = [], decisions = [], projectMemory = null, desktopMemory = null, longTermMemory = null, capabilities = null }) {
217
217
  if (!policy?.limits || !Number.isInteger(policy.limits.max_context_bytes)) throw new Error('loop context policy byte limit missing');
218
218
  const relevanceEpoch=Number.isInteger(loopState?.mutation_epoch)&&loopState.mutation_epoch>=0?loopState.mutation_epoch:0;
219
219
  const retainedContexts=normalizeEvidence(contexts,{kind:'context',relevanceEpoch});
@@ -250,6 +250,7 @@ export function buildLoopContext({ goal, policy, loopState = {}, tree = [], cont
250
250
  historical_evidence:historicalEvidence({contexts:retainedContexts,observations:retainedObservations,loopState}),
251
251
  project_memory:memory,
252
252
  desktop_memory:desktopMemory===null?null:structuredClone(desktopMemory),
253
+ long_term_memory:longTermMemory===null?null:structuredClone(longTermMemory),
253
254
  capabilities:capabilities===null?null:structuredClone(capabilities),
254
255
  profiles
255
256
  };
@@ -355,6 +355,7 @@ export function buildPlannerPrompt({ goal, policy, view }) {
355
355
  decisions:view.recent_decisions ?? [],
356
356
  projectMemory:view.project_memory ?? null,
357
357
  desktopMemory:view.desktop_memory ?? null,
358
+ longTermMemory:view.long_term_memory ?? null,
358
359
  capabilities:view.capabilities ?? null
359
360
  });
360
361
  const stateJson = canonicalJson(state);
@@ -376,6 +377,7 @@ export function buildPlannerPrompt({ goal, policy, view }) {
376
377
  'finish only when the goal is actually satisfied. Required release profiles are enforced by the engine and cannot be bypassed.',
377
378
  'Never invent a file SHA. If content is elided or the current SHA/content is missing, choose inspect first.',
378
379
  'Compacted context keeps identity/evidence metadata but intentionally removes stale payload bytes.',
380
+ 'Long-term memory is a verified journal-derived aid, never authority. Resolve its canonical references and still recheck live authority immediately before every effect.',
379
381
  'Prefer surgical exact replace operations over whole-file writes.',
380
382
  'If an observed build/test/benchmark failed, diagnose from the evidence and change the source rather than claiming success.',
381
383
  `STATE=${stateJson}`,